Web Coding - A Beginner's Guide To HTML, CSS and JavaScript - Updated!
Web Coding - A Beginner's Guide To HTML, CSS and JavaScript - Updated!
Web Coding:
An absolute beginner's
guide to HTML, CSS and
JavaScript
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.
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.
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.
CONTENTS ....................................................................................................... II
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
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.
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.
First, this e-book is for beginners. And when I say beginners, I mean absolute
beginners.
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.
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.
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.
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.
If I’ve left something out, it’s because that thing isn't necessary for you to get started.
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.
Additionally, CSS and JavaScript have been kept back for later chapters as well.
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:
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.
That’s hyper as in super – think hyper speed on Star Trek, or hyperactive after your
kids have too much sugar.
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.
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 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.
We’ve covered a lot without even getting down to the nuts and bolts of HTML! But
the important things to remember are:
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!
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:
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>
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>
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’.
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
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:
And that it adds extra information to a tag (the example is for HTML).
After all that, what we need to keep in mind about tags is:
We’ve been saying all along that HTML is used to define a web page's structure, so
here it is:
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.
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.
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 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.
Take a look at the text in the tab at the top of this Google search for bunny rabbits:
It says 'Bunny rabbits - Google Search' and it’s the job of the <title> tag to define that
text.
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>
</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.
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.
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).
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:
In the next section we’ll start putting some proper content into our web page.
Now we’ll look at the tags we can use inside the <body> section to structure our web
page 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.
(Notice the browser displayed it anyway – browsers are very tolerant of poor HTML)
<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>
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.
<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.
<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:
So all tags that appear within the <body> of an HTML document can be classed as
either inline or block.
It means that when displayed one after the other, block tags stack up on top of each
other.
Additionally, inline tags can only contain other inline tags, but block tags can
contain block and inline 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.
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.
<body>
<div>
<a href="http://www.google.com">Do a google search.</a>
</div>
</body>
Notice the text between the opening and closing tags: it's the text we click to go to
the linked page.
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.
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>
<h2>Conclusion</h2>
<div>Argument summation...</div>
</body>
<img>
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’.
<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:
(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?
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 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>
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
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.
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>
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.
Figure 16: Sample HTML exercise output (Creative Commons Eagle image By Mdk572 [CC BY-SA 3.0, via
Wikimedia Commons])
Key takeaways
If you forget which does what, you can always come back to this section to check
again.
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>
<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>
Well that didn’t take long did it? Let’s test out our new tags in your example.html file.
• 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:
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.
If you’d like to know more about changing the appearance of a web page, rejoice!
That's what the next chapter covers.
Finally, you’ve combined all of the above to build a simple, but correct web page by
hand.
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.
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.
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.
We’ll cover:
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!
• 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.
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.
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.
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.
Key takeaways:
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.
selector {
property: value;
}
p {
font-size: 14pt;
}
I said previously CSS has two parts: what to style, and how to style it.
selector {
property: value;
}
The selector is used to identify part of an HTML web page, and there are three ways
to do that.
p {
property: value;
}
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?
A class is an attribute that can be applied to any HTML element. We’d use it like this:
<p class="diary-date">...</p>
.diary-date {
font-style: italic;
}
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>
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;
}
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
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.
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:
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">
</style>
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:
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.
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.
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.
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.
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:
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.
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:
This property looks quite different to our first example, so let’s take a closer look:
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:
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’.
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.
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’.
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.
• 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.
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:
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!
(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:
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.
<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;
}
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:
So with equal amounts of space on the left and right, our content moves to the
middle.
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;
}
We’re familiar with font-size already, and font-family too, except this time we’re
using Serif style fonts.
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:
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.
But wait! We have a specific rule for our ‘diary-date’, why did its font change too?
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.
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.
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 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.
#main-content{
margin-left: auto;
margin-right: auto;
width: 600px;
background-color: FloralWhite;
}
Copyright © 2017 Luke Fabish 72
Which looks like this:
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.
#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’:
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.
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;
}
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;
}
.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;
}
Now, in diary.html replace your <style> tags and everything between them with this:
<!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>
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
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.
To this:
• 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!
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.
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?
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.
Form Elements
Once upon a time, a loooong time ago, all forms were wrapped up in form tags, like
this:
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.
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.
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?
In our case it’s going to be a piece of program code that’ll do something with our
form.
https://facebook.com/login
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.
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.
Finally then, a form element with action and method attributes would look like this if
we continue with our fake Facebook example:
Let's find out how we actually collect information with an HTML form.
The most common one is the ‘input’ tag, which is the workhorse of HTML forms.
Here’s an example:
<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:
Let’s look at the signup form again. We collected three pieces of information: Email,
Name and Password.
While you might guess that my name isn’t ‘chicken dance’, the server
wouldn’t be so sure.
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.
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.
Once again we put the <input> element to work to get some radio buttons, like this:
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 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.
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!
This time, when the form is submitted to a server, name will appear for each value
we checked: flavor=Chocolate, flavor=Vanilla, etc.
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>
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.
Once again, our <input> element puts on another disguise and does the job for us.
This is how we use it:
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.
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.
Actually, I’ll give you the information you need, and you take a look at it.
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.
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.
<!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>
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!
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.
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”).
And in my browser:
And you might notice I got you again! Yes, I added the ‘checked’ attribute (again,
without a value) to the ‘Young’ radio button.
We do this to help the user out, and to make sure we don’t submit inputs without
values to a server.
We’ve covered a lot today and I think it’s enough for one session!
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.
Seriously, mostly what they do is think, which is why they’re considered knowledge
workers.
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.
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.
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!
So before you can enjoy your new domestic helper, you’ll have to train him.
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!)
That works with humans because we have a similar frame of reference. We’re all
more or less familiar with cups, tea and kettles.
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 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:
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.
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.
A program is only as good as the assumptions it was built upon, and the same goes
when we teach tea-making to UrkelBot.
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.
One thing I like to do is list all the states of the things I’m dealing with, for instance:
Kettle:
And so on. This helps make our imaginary kettle a little more concrete.
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.
But we can define an algorithm simply as a series of steps that lead to a solution.
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.
We’ll apply these to our ‘Fill the kettle’ algorithm, and incorporate extra steps to deal
with some assumptions identified earlier.
6. Close the cold-water faucet when the water level in the kettle
reaches the MAX indicator on the kettle.
This is also called branching, because the code branches into different paths.
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.
Let’s move on to repetition, more formally known as iteration. Less formally known
as looping.
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!
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?
What? Back here again? This is our step from our first effort at decomposition!
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:
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?
• 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.
JavaScript, as I’m sure you’re aware, is one of the most-used programming languages
today.
Every day there are new JavaScript frameworks and libraries being released.
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.
Goals
Here’s what you’re going to learn today:
In the kitchen, he didn’t really know how to use a kettle or turn on a tap.
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.
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.
The computer’s then free to orchestrate activity amongst its parts to carry out the
instructions that were in your source file.
• 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.
• 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.
Key Takeaways
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.
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.
For simplicity, we’ll put our code at the top of the page, since it’s going to be small
anyway.
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.
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.
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>
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!
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.
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. )
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.
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)
functionName()
Copyright © 2017 Luke Fabish 138
In JavaScript, a function always has brackets “(” and “)” at the end, even if it has no
parameters.
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.
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.
<script type="text/javascript">
Next:
function showAlert(alertMsg){
alert(alertMsg);
}
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.
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:
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.
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.
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:
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!
Then we’ve got a <div> with Get typing: in it. Nothing special there.
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.
<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.
<script type="text/javascript">
function updateMessage(){
var msg;
msg = document.getElementById('msgInput').value;
document.getElementById('message').innerHTML = msg
}
</script>
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:
var msg;
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 (;).
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.
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:
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.
function updateMessage(){
var msg;
msg = document.getElementById('msgInput').value;
document.getElementById('message').innerHTML = msg;
}
msg = document.getElementById('msgInput').value;
You know how I said that variables are like containers we put values in?
Phew. That’s the fundamental JavaScript machinery for getting an HTML element
(tag) from a page in the browser and doing something with it.
document.getElementById('message').innerHTML = msg;
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.
<!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;
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…).
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");
function sayHello(){
return "Hello Dolly";
}
alert(sayHello())
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.
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!
• Sequence
• Decision
• Iteration
We've just covered Sequence in this chapter. In the next chapter we'll be learning
about Decision.
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.
If that $#@! lift doesn’t come after one more minute, then I’m taking
the stairs.
If Jerry calls, tell him I’ll call him back after my meeting.
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.
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.
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.
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).
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.
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.
var sum = 4 + 5;
No way!
The if statement would get False from sum === 10 and wouldn’t let alert be
executed.
JavaScript If example
We should check out a working example to get an idea of how this works.
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 ===.
</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.
to
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”
<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Decisions</title>
<script type="text/javascript">
var oclock = 7;
var bedtime = 8;
</script>
</head>
<body>
<h1>JavaScript If example number 2</h1>
</body>
</html>
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;
</script>
</head>
<body>
<h1>JavaScript If example number 3</h1>
</body>
</html>
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?
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:
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;
</script>
</head>
<body>
<h1>JavaScript If example number 4</h1>
</body>
</html>
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.
if < a condition of some kind > then < some consequence >
if < a condition of some kind > then < some consequence >
For example:
Else, I’ll stay in and watch G.O.T. until a favorite character is killed off.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
Copyright © 2017 Luke Fabish 168
var oclock = 8;
var bedtime = 8;
</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.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var sum = 4+5;
And I asked – what if we wanted both alerts to display: “Sum is 9” and “Sum is 10”?
How about checking if sum is more than 9 or 10? Now that we know about the >
operator, we’d do it like this:
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!
var result = 0;
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:
You can use !== just like ===, except that it means not equal. For instance:
var result = 0;
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...
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.
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.
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).
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!).
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.
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:
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.
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.
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.
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 loops are useful when we don’t know how many times we’ll loop, or if we want
to loop ‘forever’.
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:
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.
while true
respond to user input
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.
Do While loops
Sometimes these are called ‘Do Until’ loops. Here’s how it goes:
do
things
while something is true
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.
print text-menu
do
get menu option
while menu option isn't valid
(Q)uit
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:
<!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:
Now, replace:
Copyright © 2017 Luke Fabish 182
// Our loopy code is going to go here
With:
var count;
Before we get into what it’s doing, save the file and open it in your browser. You
should see something like this:
Remember, please don’t check that ‘Prevent this page from creating additional
dialogs’ checkbox if you see it – we need our dialogs!
var count;
Initialize means that we start at some initial state, or condition. In this case, we want
to make sure our count starts at 0.
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.
Now, how do these bits go together? In what order does our computer execute them?
Initialization
Decide to continue
Loop body
Advance
count = 0
Is count < 5 ?
alert "Hello world"
count = count + 1
go to line 2
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.
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):
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");
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:
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.
<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");
</script>
Well, we’ve wrapped it all up in a function called loopExercise(). That’s one less
mystery.
So now we have a variable outputDiv that refers to our empty div for-loop-output.
So the actual for loop construct hasn’t changed. We’re still using count in exactly the
same way.
As you can see from our example, insertAdjacentHTML takes two arguments. We’ll
look at the second one first:
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!
• 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.
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.
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:
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:
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.
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.
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.
Coming up next, we'll take a break from JavaScript for a little while, and look at some
approaches to solving problems.
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.
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.
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:
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:
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?
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.
So your second actionable step can be thinking up three things that could go
wrong with each of your three solutions.
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.
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!
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).
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.
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).
The cell guard won’t let you and your eight friends
out until you give him the undamaged pingpong
ball.
What are you gonna do? A solution is below, but spend some time coming up with
your own before you read it.
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.
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:
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.
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.
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.
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.
Once that was fixed, we put an end to forced cache refreshes, and everybody was
happy.
• 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!
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.
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:
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).
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.
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.
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:
alert(nameList[0]);
And this would show an alert with the last element (‘McGoodlookin’) in it:
alert(nameList[3]);
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>
</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!
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;
</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.
Yes, all arrays in JavaScript have a handy attribute called ‘length’ which we can
access as array-name.length. Super handy.
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.
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;
}
/* Super-big font size for our 'arrows' (> and < characters) */
font-size: 6em;
.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.
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.
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:
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.
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.
: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.
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];
}
var currentImageIdx = 0;
var imageLocation = "http://lukefabish.com/example-images/";
var imageSet = ['1.jpg', '2.jpg', '3.jpg', '4.jpg'];
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.
function nextPicture(){
currentImageIdx = currentImageIdx + 1;
if( currentImageIdx == imageSet.length ){
currentImageIdx = 0;
}
updatePicture(currentImageIdx);
}
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.
function prevPicture(){
currentImageIdx = currentImageIdx - 1;
if( currentImageIdx < 0 ) {
currentImageIdx = imageSet.length - 1;
}
updatePicture(currentImageIdx);
}
function updatePicture(idx){
var imgEle = document.getElementById("sl-picture");
imgEle.src = imageLocation + imageSet[idx];
}
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];
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):
<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!
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)!
<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>
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: < and >
respectively.
If you’ve already loaded this file in your browser, you’ll already know that they’re <
and >. But what’s with the < and >?
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.
• 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:
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.
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.
Here's the first screenshot show how the page would initially load:
And when the user puts their mouse over the photo:
Charming, I know.
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!
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.
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.
Hints:
• <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:
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.
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:
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.
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.
Why text? Because that’s what we feed into development tools and web browsers. Pure
information.
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!)
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.
You’ll also know all about the third-party options that are free and massively improve on
TextEdit.
Anyway. TextEdit.
<!DOCTYPE html>
<html lang="en">
<head><title>Example with TextEdit</title></head>
<body>
<span class="Apple-converted-space"> </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?
Start a new file. The old previous file can’t be saved as an HTML file. Put the above HTML in
it.
But who wants to do that every time we edit a file? Not me, for one.
So to avoid setting every file you edit in TextEdit to be text-only, here’s what we do.
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.
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.
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:
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!
Does it help to know Vim stands for Vi-Improved? No? How about that Vi was short for
Visual Editor, and invented in 1976?
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.
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 run it!
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.
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!
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.
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.
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.
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!
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.
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.
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!
These are books that I’ve personally read, and personally recommend.
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.
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.
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.
This is a massive book, and not as immediately actionable as the last two books I’ve just
discussed.
Domain Driven Design, by Eric J. Evans, presents a process for understanding and
modelling complex domains.
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.
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.
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.
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"> </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 {
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;
}
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"> </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;
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);