Get Coding! Learn HTML, CSS, and JavaScript and Build A Website, App, and Game PDF
Get Coding! Learn HTML, CSS, and JavaScript and Build A Website, App, and Game PDF
CODING!
GC0_p1-15_9781406366846_PI_UK.indd 1 15/02/2016 15:47
CONTENTS
INTRODUCTION .............................................6–11
INDEX ...................................................206–207
ne
D
.
you new HTML, CSS and JavaScript
Prof
Great to
coding skills. Your job is to work through meet you!
the chapters and use your skills to
complete the missions. You will be joining
Professor Bairstone, Dr Day and Ernest,
who need your help to keep a valuable
diamond safe.
est
Ern
We hope you enjoy this book and it inspires you to get coding!
Perfect programming
Computers are electronic devices that can process
information. They can be the size of a room or fit
inside tiny gadgets, and do all kinds of complex tasks.
Computers are made up of hardware (the physical Facebook
parts of a computer you can touch) and software Google
(the parts you can’t touch). Computers need software
because they can’t think or act by themselves. They iTunes
have to follow a detailed series of commands in a Microsoft Word
piece of software known as a program. Programs are
written in programming languages that computers can Minecraft
understand. Writing programs is therefore known as
YouTube
coding or programming. You can write programs
to do all sorts of things. You might have used some
of these:
TML css
H
10
11
Mission Briefs
dy> e>
A st
has olen di
<scr been amond
ip foun
var t> d!
a di am
</ lert(d ond
</bo script iamo = 300
</ht dy> > nd); ;
ml>
12
13
PC On a PC, you’ll find Notepad by going into the Start menu and typing it in the search bar.
On a Mac, you’ll find TextEdit by typing it in the Spotlight search magnifying glass in
Mac the top-right of your screen. When you open TextEdit, you need to do the following things:
• Set up your file as a plain text (rather than rich text) file. To do this go to Format
in the menu bar and select Make Plain Text.
• Also go to TextEdit in the menu bar. Select Preferences. In the New Document tab in
the Format section, make sure Plain text is checked. In the Options section, make sure
Smart quotes is unchecked.
• In the Open and Save tab in Preferences, make sure Display HTML files as HTML code
instead of formatted text is unchecked.
14
15
Dear Coder,
I am currently on an expedition
in the mountains of Siberia, with
Dr Ruby Day and my dog Ernest. the top scientist
The aim of our expedition was to
fossils. Instead we have made an find prehistoric
even more sensational discovery.
We were exploring a cave when
Ernest suddenly started barking
a large boulder. We looked closer and sniffing at
and saw that something had bee
crack in the rock-face. Dr Day pull n hidden in a
ed out the object. It was a small
oilcloth. When I opened the box box, wrapped in
, I couldn’t believe my eyes.
It was the legendary Monk Diam
ond! As I’m sure you know, the Mon
was stolen from Moscow three year k Diamond
s ago in a daring robb
obbery and its whereabouts
has been unknown until now. Our
discovery is of great internationa
l significance.
We can only access the Internet
briefly, using my emergengency booster pack.
Dr Day and I were hoping you cou
ld help us by using youourr Code Skills to build
a web page about our exciting disc
overy.
I’m attaching an entry from the Exp
lorer’s Encyclopedia,, which will tell
about the Monk Diamond’s rem you all
arkable history. You can use the
to build your web page. We will information
use the page to announncece our discovery to
the world the moment we arrive
in Moscow.
Thank you for helping us with this
exci ting mission. It’s goin
oingg to be great!
Warmest wishes from the chilly
mountains,
Professor Harry Bairstone
T HE E XPLORER ’ S This entry is about the Monk Diamond. For other jewels, see Diamonds.
ENCYCLOPEDIA
The Guide to Every Adventure
The Monk Diamond is one of the rarest and most precious diamonds in the world,
Home page famous for its distinctive green colour. It was discovered in 1880 and was bought by
Contents a Russian nobleman for his wife in 1889.
Featured discoveries
Famous explorers During the Russian Revolution, the Monk Diamond was stolen from the nobleman’s
Historical expeditions palace in St Petersburg. For the next 30 years, the Monk Diamond’s whereabouts
The Monk
Diamond
Cut: Oval
Carats: 300
Clarity: Flawless
Value: Over £10 million
was unknown. In 1947 it was discovered during a police raid on a gang of petty criminals in Moscow. It was
returned to the nobleman’s family.
The nobleman’s son decided the Monk Diamond was unlucky and sold it to the House of Volkov, Moscow’s
oldest jewellery house. The House of Volkov paid an undisclosed sum for the jewel, but it was rumoured to be
the most expensive diamond sale ever.
The Monk Diamond was on display in the House of Volkov’s private collection until three years ago, when it was
stolen in an audacious raid. Despite a long investigation and the promise of a huge reward, the police were
unable to track down the culprits and the case remains unsolved.
The thieves are believed to be the Bond Brothers, the international gang of jewel thieves responsible for
numerous high profile thefts. A theory put forward by the explorer Professor Bairstone is that the Monk Diamond
was smuggled out of Moscow by the Bond Brothers and hidden somewhere in Russia. He thinks “the thieves are
biding their time until they can sell the diamond on the black market without attracting suspicion.”
This is the paragraph <p> tag. When tags come in pairs, we call the first tag the opening tag and the
second tag the closing tag. You can spot a closing tag because it contains a forward slash (/). When
your browser reads this code it understands that you are telling it to group the text between the opening
and closing <p> tags into a paragraph.
To code a web page you have to create a HTML file in a text-editing program. Your browser expects
some tags to appear in a certain order. You need to code the tags that contain instructions about the
whole page first. Then you code the tags with instructions for specific pieces of content on your page.
Tags can be put inside other tags. You just have to remember to close each tag when you’ve finished with it.
20
<!DOCTYPE html>
This is called the <!DOCTYPE> declaration and it is always <html>
the first line of a HTML file. It tells our browser what version of This is the <html> tag and it tells the
HTML our page has been coded in. It is not a HTML tag so it browser that we have used HTML to
is written with capital letters and it doesn’t need a closing tag. code our page.
<!DOCTYPE html>
<html> <title>
<head> The <title> tag
<head> <title> goes inside the
This is the <head> The Monk Diamond Discovery <head> tag. The
tag. Inside are </title> content between the
pieces of content </head> tags will not appear
that aren’t displayed <body> in the main body
in the main <body> <p>Professor Bairstone and Dr Day have of our page. It will
of your page, like discovered the Monk Diamond.</p> be the title of the
the title. You can </body> browser window
also put instructions </html> when you open
that you want your the page in your
browser to apply browser.
to your whole
page here. <body> <p>
All the content you want to see displayed This is the paragraph tag.
you web page goes inside the <body>
in your All the text between the
tag. So
S this text about the Monk Diamond opening and closing tags
will appear
ap on our page when we open will be grouped into a
the file in our web browser. paragraph.
21
Writing HTML
Now you know what HTML tags are and how they is as accurate as possible. Having a letter or a
work, it’s time for you to have a go at using them. symbol wrong or missing could stop your code
The best way to learn new pieces of code is to from working, as your browser won’t be able to
practise writing them. Throughout this book you will understand your instructions. If you are having
find Code Skills. Follow the step-by-step instructions problems making a program
in the exercises and learn new skills each time. work, it’s a good idea to
It’s really important to make sure your code check the following things:
That you’ve not missed out any tags or used them in the wrong order
That there are no typos or spelling errors in your code
That you’ve used correct capitalization throughout your code
These are some top
That you’ve included all the symbols you need, in the right order
tips for writing code!
That you’re using straight quotes (" ") and not curly quotes (“ ”)
That you’ve closed all your tags by including the forward slash (/)
That your text-editing program has saved your file as a HTML file (.html)
If you’re still stuck, go to the Get Coding! website (www.getcodingkids.com) where you will be able to
copy and paste the code block you need.
22
Let’s use HTML tags to code a very simple web page. Follow these steps to
learn how to structure a HTML web page that is made up of a title and a
piece of text.
1. Open up your text-editing program. Look back 4. Open your HTML file in your web browser.
at Key Code Skill 2 on page 14 if you need a See Key Code Skill 4 on page 15 if you need
reminder about how to do this. a reminder about how to do this. Your code
will be displayed on-screen as a web p
page,
2. Type this code into your text-editing program: like this:
The Monk
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond</title> The Monk Diamond is a rare jewel.
</head>
<body>
<p>The Monk Diamond is a rare jewel.</p>
</body>
</html>
Make sure you copy the code carefully. Then open your file in your text-editing program
Your web browser won’t be able to read again. Change the text between the opening
your code if there are any mistakes in it. and closing <title> tags and <p> tags
The <!DOCTYPE> declaration has to have to text of your choice. Save your file.
capital letters and your last tag always has
to be </html>. Check you have closed each 5. Press the Refresh button in your browser. On a
tag by including the forward slash (/). PC, press F5. On a Mac, press Command+R.
Your changes to the text will appear on-screen.
3. Save your file in your Coding
folder as a HTML file (.html). Call it
webpagetemplate.html. Go back You just built your
to Key Code Skills 1 and 3 on pages 13 and first web page!
14 if you need a reminder about how to do this.
23
<body>
The <p> tag is nested
Indent <p>The Monk Diamond is worth over £10 million.</p> inside the <body> tag
</body>
<body>
Opening
paragraph <p>Professor Bairstone and Dr Day have made a sensational discovery.</p>
tag <p>They have discovered the Monk Diamond in a remote cave in Siberia.</p>
</body>
Closing
paragraph tag
24
<body>
<p>Professor Bairstone and Dr Day have made a sensational discovery.<br/>
Professor Bairstone is the world's leading explorer.<br/>
Line break tag
Dr Day is a scientist who studies fossils.</p>
<p>They have discovered the
e Monk Diamond in a remote cave in Siberia.</p>
</body>
The Monk Di
tag are used this way. ed the Monk Diamond in a remote cave in Siberia.
They have discovered
You can spot a self-closing tag
because the forward slash (/)
comes at the end of the tag, rather
than at the beginning as it does for Now it’s your turnn to
a regular closing tag. ing
have a go at using
these new tags!s!
25
<p>The Monk Diamond has been Ernest, Professor Bairstone's dog, found the jewel.
discovered in Siberia.</p>
<p>Ernest, Professor Bairstone's
dog, found the jewel.</p> I think it’s time
</body> t learn about
to
Great work! But what t image tag!
the
about some pictures of
the Monk Diamond?
26
CODE
S
of giving your browser extra
<img src="image.jpg"/> information about a HTML element.
There are lots of different kinds of
attributes you can include in your tags.
The equals sign (=) and double quotes
(" ") set the value of the source attribute There are two parts to an attribute: the
attribute name and the value of the attribute.
You have to include the source attribute in the You use an equals sign (=) to set the value
<img/> tag so your browser knows where to find of the attribute and put the value in double
your image. Without it your browser won’t know quotes (" "). So an attribute will always look
what to display on-screen. The value of your source like this: name="value". Attributes are added
attribute can either be set to a file name of a saved to the opening tag, or to the only tag (in the
image or a URL (web address) of your image. case of a self-closing tag).
<body>
Image <p>Professor Bairstone has sent us this secret photo of the Monk Diamond:</p>
tag <img src="diamond.jpg"/>
</body>
Source File name
attribute
27
If there’s an image on the Internet you want to use on your web page, you have to set the value of the
source attribute in your <img/> tag to the URL of the image. You find the URL of a picture by right-clicking on
it and selecting Copy image URL on a PC or Copy image address on a Mac. You then paste the URL inside
your <img/> tag as the value of the source attribute. Don’t forget to put it in double quotes (" "), like this:
<body>
<p>This is Professor Bairstone and Dr Day's first expedition together.</p>
<p>Here is a photo of the team:</p>
<img src="https://getcodingkids.com/team_photo.jpg"/>
c
</body> The Monk D
Naming an image
<body>
<p>This is Professor Bairstone and Dr Day's first expedition together.</p>
<p>Here is a photo of the team:</p>
<img src="https://getcodingkids.com/team_photo.jpg" alt="The Team"/>
</body>
28
PTO
29
6. Go to the images section of the Get Coding! website. Find the photo of the team. Right-click and select
Copy image URL or Copy image address depending on your system. Paste the URL into your source
attribute, like this:
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond</title>
</head>
<body>
<p>The Monk Diamond is a rare green colour.</p>
<img src="diamond.jpg" alt="The Monk Diamond"/>
<p>The team was delighted with their discovery.</p>
<img src="https://getcodingkids.com/team_photo.jpg" alt="The Team"/>
</body>
</html>
Save your file and refresh your page. Doesn't Ernest look
Depending on your browser, you may see proud of himself?
the text in the alt attributes if you hover your
mouse over the images.
30
31
Now it’s your turn to have a go at using the <div> tag. Master this skill and
you’ll then be able to make a web page with an interesting layout.
1. Open up your text-editing program. Create a new HTML file called divs.html. Then copy and paste
your code from webpagetemplate.html into your new file. Modify the code so that it looks like this:
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond</title>
</head>
<body>
<p>Professor Bairstone is a famous explorer.</p>
<p>Dr Day is a top scientist. She loves dinosaur fossils.</p>
</body>
</html>
2. Now add two <div> tags between the opening and closing 3. Save your HTML file and open
<body> tags. Put each paragraph inside a <div>, like this: it in your browser. Your <div>
tags won’t have changed
<body> anything on-screen, but your elements
<div> will be grouped together, ready for
<p>Professor Bairstone is a famous you to design and position.
explorer.</p>
The Monk D
</div>
<div>
<p>Dr Day is a top scientist. She loves Professor Bairstone is a famous explorer.
dinosaur fossils.</p>
Dr Day is a top scientist. She loves dinosaur fossils.
</div>
</body>
33
Just like we saw earlier, the value of our style attribute is set using the equals sign (=) and enclosed in
double quotes (" "). We apply CSS to our HTML tag by setting the value of the style attribute to CSS. CSS
is a very simple programming language to write. It’s always split into two parts: a property and a value.
style="CSS-property: value;"
WORD SYNTAX is the
Hyphen Colon
CODE
Semi-colon
S
set of rules which
decide the way a programming
Your browser has hundreds of different built-in language is structured and written.
CSS properties and values that you can use in
your HTML tags to change your page.
Let’s take a closer look at how we can use Look at how we can use
CSS with <div> tags. If we want to change the HTML and CSS together
background colour of a section of our page, to change our page!
we can use CSS and HTML like this:
Style CSS
attribute property CSS value
<body>
<div style="background-color: green;">
<p>The Monk Diamond had been hidden in a cave.</p>
<p>It was inside a crack in the rock.</p>
</div>
</body>
Did you
notice?
The Monk Di
35
<body>
<p>THE STOLEN MONK DIAMOND IS DISCOVERED!</p>
Background-color property
<div style="background-color: green;">
<p>Professor Bairstone, Dr Day and Ernest were on an expedition.<br/>
They made an exciting discovery in the mountains.</p>
</div>
<div style="background-color: cyan;">
<p>Ernest started sniffing and barking at a rock in a cave.<br/>
Hidden inside the rock was the Monk Diamond.</p>
</div>
</body>
The Monk Di
T
Did you
notice?
There are thousands of colours that you can use as values in CSS. Go to
www.w3schools.com/cssref/css_colornames.asp to view more of them.
36
It’s time for you to start using CSS with HTML. Have a go at adding the style
attribute to a HTML tag and then setting a CSS property and value.
4. Save your HTML file and open it The jewel was stolen from Moscow.
in your browser. Try changing the
The theft happened three years ago.
value of the background-color CSS
property to different colours. Save your The Bond Brothers are the prime suspects.
37
background-color Sets the colour of your background red; black; white; yellow;
color Sets the colour of your text red; black; white; yellow;
WORD
Graphics on your computer screen are made up of tiny coloured dots called PIXELS
CODE
(px). You can tell your browser how many pixels you want to be in a HTML element.
38
39
40
Measurements in CSS
There are lots of different units you can use for Types of unit:
measuring in CSS. Make sure you tell your browser
Pixels (px)
what unit you are using by typing it after the number
value. Here are some of the most common: Percentages (%)
Points (pt)
41
<body>
<div style="background-color: palegreen; height: 75%; width: 50%;">
<p>The police remain baffled by the crime.</p>
<p>There were no successful leads in the case.</p> Percent value
</div>
</body>
The Monk Di
Did you
notice?
The police remain baffled by
When you calculate percentages you are the crime.
calculating what percentage of the screen
There were no successful
you want your element to fill. If you change leads in the case.
the size of your browser, the size of the
element will also change.
42
</body>
43
1. Open up your text-editing program and create a new HTML file called CSSproperties.html.
Copy and paste your code from CSS.html into your new file and modify it so that there are three
<div> tags, like this:
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond</title>
</head>
<body>
<div>
Why was the diamond hidden in a cave?<br/>
Who hid it there?
</div>
<div>
Was it the Bond Brothers?<br/>
Could they be watching the cave?
</div>
<div>
Is the team safe?<br/> I really hope
Their camp
p is very
y remote. we're not in
</div> danger!
</body>
</html>
We have to
keep the
diamond safe!
44
3. Change the width and height of your second <div> using the width and height CSS properties.
Make your <div> 75% of the width of your page and 100px high. Add a background colour
and margin to your <div> too. Your code will look like this:
4. Let’s try moving our third <div> to a different position on the page. Use the float CSS property to
move your <div> to the right of your page. Also add a border and some padding to the <div>
using the border and padding CSS properties. Your code will look like this:
45
<!DOCTYPE html>
<html>
Head tag
<head>
<title>The Monk Diamond Discovery</title>
</head>
<body>
<p>Professor Bairstone and Dr Day have discovered the Monk Diamond.</p>
</body>
</html>
In every page we’ve built so far, the <title> tag The Monk
46
<head>
Style tag <title>The Monk Diamond Discovery</title>
<style>
CSS class name Opening curly brace
.text {
Dot text-align: center;
font-size: 18pt;
CSS
properties background-color: aqua;
}
Closing
</style> curly brace
</head>
This is a different way of writing and structuring want to apply to the HTML element. As before, you
our code. CSS classes always start with the class separate the property from the value with a colon
name. It’s up to you what you name your CSS (:) and after the value put a semi-colon (;).
classes, but before the class name there has to In this example we have created a CSS class
be a dot (.). Then there is a pair of curly braces which we have named “text“. Every time we use this
({ }). The curly braces tell your browser where the CSS class we will change the text-align, font-size
instructions it needs to follow begin and end. Inside and background-color CSS properties to the values
the curly braces you put all the CSS properties you we
we’veve selected.
47
<!DOCTYPE html>
<html>
<head> CSS classes and
<title>The Monk Diamond Discovery</title> the class attribute
<style> are the best way to
.text { S.
write CSS.
text-align: center;
CSS class font-size: 18pt;
background-color: aqua;
}
</style>
</head> Class attribute
<body>
<p class="text">The Monk Diamond Discovery</p>
<p>The Monk Diamond has been discovered in the mountains of Siberia.</p>
<p class="text">The discovery is of great international significance.</p>
<p>The team were looking for fossils.</p>
<p class="text">Not one of the world's most famous jewels.</p>
</body>
</html> The Monk Di
sign (=) and double quotes (" ") to set its The team were looking for fossils.
48
Professor Bairstone
one
is going to be so
Here are some our
pleased with your
im
important things web page!
to remember when
y write CSS!
you
49
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond</title>
</head>
<body>
<div>
The Monk Diamond<br/>
An incredible discovery
</div>
<br/>
<div>
Stolen diamond found on expedition in Siberia!
</div>
<br/>
<div>
Professor Bairstone and Dr Day were looking for fossils in Siberia.<br/>
They found the stolen diamond hidden inside a remote cave.
</div>
</body>
</html>
50
PTO
51
<div class="body">
Professor Bairstone and Dr Day were looking for fossils in Siberia.<br/>
They found the stolen diamond hidden inside a remote cave.
</div>
The Monk Di
9. Save your HTML file
and open it in your
browser. You will
see that each CSS class
changes the design of a <div>.
The Monk Diamond
An incredible discovery
G work! But
Good Stolen diamond found on expedition in Siberia!
reme
remember that I was
the one who sniffed Professor Bairstone and Dr Day were looking for
fossils in Siberia.
ou
out the diamond! They found the stolen diamond hidden inside a
remote cave.
52
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond</title>
The Monk Di
<style>
.header {
background-color: lightgreen;
width: 70%;
height: 50%; The Monk Diamond
} An incredible discovery
.text {
text-align: center;
font-size: 18pt;
}
.padding {
padding: 25px;
This is how we add more
} than one CSS class name
</style> to our class attribute
</head> Using CSS classes to
<body>
select HTML elements
<div class="header text padding">
The Monk Diamond<br/> Another handy thing you can do with CSS
An incredible discovery classes is use them to change the CSS
</div> properties of a type of HTML element. To do
</body> this you use something called the element
</html> selector. To use the element selector, you use
the name of the element you want to change
as the name of your CSS class. You shouldn’t
Turn over to find include the dot before the name of your CSS
out more about the class. You also don’t need to include a class
element selector. attribute in the <body>.
<!DOCTYPE html>
<html>
<head>
<title>The Monk Diamond Discovery</title>
<style>
Element
selector p {
font-size: 16pt;
text-align: center;
background-color: lightblue;
}
</style>
</head>
<body>
<p>The Monk Diamond was discovered by Professor Bairstone and Dr Day.</p>
<p>Ernest alerted them to its hiding place.</p>
<p>It had been hidden in a crack in the rock.</p>
</body>
</html>
The Monk Di
54
Build a web page about the discovery of the Monk Diamond. Use HTML and CSS to add
text and images and create an interesting design. Include these things on your page:
A header banner
A title banner
Text about the Monk Diamond
An image of the team Turn over to see
a code block for a
An image of the diamond finished web page.
A Monk Diamond fact file
55
<!DOCTYPE html>
<html>
<head>
The Monk Diamond Discovery
<title>The Monk Diamond</title>
<style>
Stolen Diamond Discovered in Siberia!
body {
Professor Bairstone and Dr Day have made a sensational discovery.
They have discovered the Monk Diamond in a remote cave in Siberia.
margin: 0px;
Professor Bairstone's dog, Ernest, sniffed out the diamond.
The jewel was stolen three years ago from the House of Volkov.
}
The prime suspects in the theft were the Bond Brothers.
The team thinks the diamond had been hidden by the thieves.
They sent this photo from their camp:
.pad {
The Monk Diamond
padding: 25px;
Fact File
Carats: 300 }
Colour: Green
Value Over £10 million
.header {
background-color: lightblue;
color: green;
height: 100px;
font-size: 36pt;
text-align: center;
}
This is what your
.welcome {
p would
web page background-color: plum;
look like iif you color: white;
used this code! font-size: 16pt;
text-align: center;
height: 40px;
margin: 0px;
}
.main-text {
width: 60%;
float: left;
background-color: beige;
}
.divs {
margin: 5px;
width: 25%;
float: left;
border: 4px solid lightblue;
}
</style>
56
Dear Coder,
T HE E XPLORER ’ S This entry is about the Bond Brothers. For more information about jewel robberies,
ENCYCLOPEDIA see Jewel Thefts.
The Guide to Every Adventure
Home page The Bond Brothers are a top secret international gang of jewel thieves. According
Contents to Interpol, over the last fifteen years they have stolen gems worth a total of more
Featured discoveries
than £500 million.
Famous explorers
Historical expeditions The gang’s tactics are similar to those used by the famous gang the Pink Panthers.
REWARD OF £1 MILLION
FOR INFORMATION LEADING TO the RECOVERY OF THE MONK DIAMOND
OR ARREST OF THE GANG
The Bond Brothers typically target exclusive jewellery houses and boutiques all over the world. Their raids are
exceptionally well-planned, with the targets scoped out weeks in advance.
The Bond Brothers’ tactics have included driving 4x4s through jewellery house windows and drilling through
basements of boutiques to access valuables kept in vaults. Members of the gang have disguised themselves
as workmen to confuse staff and then smashed open display cases.
Although the police were unable to prove it, most people think that the Bond Brothers are responsible for the
unsolved theft of the Monk Diamond from the House of Volkov jewellery house in Moscow. Two members of the
gang (a man and a woman) pretended to be looking for an engagement ring. While the woman distracted the
staff, the man smashed open the Monk Diamond’s display case with a pickaxe. The two then fled in a getaway
car, which was posing as a taxi outside.
All the CCTV in and around the House of Volkov had been disabled for the hour in which the crime took place.
Interpol therefore believes that one of the gang is also skilled in cyber-crime.
The jewel was stolen three years ago from the House of Volkov.
The prime suspects in the theft were the Bond Brothers.
The team thinks the diamond had been hidden by the thieves.
They sent this photo from their camp:
The Monk Diamond
Fact File
Carats: 300
Colour: Green
Value Over £10 million
We’ve set the value of our href attribute to the URL for the Monk Diamond Discovery page. We’ve done
this in exactly the same way as we set the values of all the attributes in Mission 1: by using the equals
sign (=) and double quotes (" ") to enclose the URL. The text between the opening and closing <a> tags
becomes your link. When you click on this text you will be taken to the Monk Diamond page.
62
<body>
<a href=" "></a> Click here
</body>
<body>
<a href=" ">Click here</a> Try clicking
ingg your
</body> ink!
new link!
63
Click here to visit the Monk Diamond web page Clicking on the link in our password
page takes us to our Monk Diamond
web page. And clicking on the link in the
Monk Diamond page takes us back to our
password page.
64
Let’s learn how to use hyperlinks to link together two web pages and build
a very simple website.
1. Open up your text-editing program. Create a 3. Now create a hyperlink that connects your first
new HTML file called page1.html. Make sure page to your second page. On your first page,
it is saved in your Coding folder. Type this code add the <a> tag with an href attribute. Set the value
into your new file: of the href to the file name of your second page.
Then add some text between the opening and
<!DOCTYPE html> closing <a> tags to make your hyperlink, like this:
<html>
<head> <body>
<title>Page 1</title> <a href="page2.html">Page 2</a>
</head> </body>
<body>
</body> 4. Now open your second page. Create a
</html> hyperlink that takes you back to your first page.
Your code will look like this:
2. Create a second HTML file called page2.html.
Make sure it is saved in your Coding folder. <body>
Then copy and paste your code from page1.html <a href="page1.html">Back to Page 1</a>
into your new file. Modify the code so that it </body>
looks like this:
Save your files and open them in your
<!DOCTYPE html> browser. You will be able to link between
<html> the two pages.
<head>
<title>Page 2</title>
Page 2
Now to make
</head>
the pas
password!
Page 1
<body> Back to Page 1
</body>
</html>
Page 2
65
66
Password
Password
OK
Variables are always written in the same way. Every piece of JavaScript tells your browser a different
piece of information, and will be important when you build a program.
A variable needs:
A keyword
To define a variable you have to use the variable (var) keyword. It tells your browser
you are creating a variable.
A variable name
The next part of a variable is the variable name. You can give your variable any
name you like. The only rule with variable names is that they can’t have spaces
(so use camelCase instead) and can’t begin with a number.
A value
You then have to give your variable a value using the equals sign (=). Doing this
is called assigning a value. If the value of your variable is text, you have to put the
value in double quotes (" "). You can include spaces in your values. After the value
you have to include a semi-colon (;).
68
Equals (=): you use the equals sign (=) to give your
variable a value. You can use it to set variables to
both numbers and words. If your variable is a number, var teamMembers = 3;
it doesn’t have to be in double quotes (" "). Here’s an
example where the value is set to a number: Assignment operator
And here’s an example where
the value is set to words and var expeditionLeader = "Professor Bairstone";
needs double quotes (" "):
Arithmetic operators
Arithmetic operators are a way of using maths calculations to change the values of your variables.
They are a useful way of creating a numerical value for a variable.
Don’t forget JavaScript is case sensitive, so make sure you keep the cases the same in your code block.
Also remember the semi-colon (;) at the end. If you save your HTML file and open it in your browser,
nothing will happen – but don’t worry. You have stored 300 in your diamondCarats variable.
<script>
var teamMembers = 2 + 1; 3
alert(teamMembers);
</script>
OK
<script>
var jewelThieves = "The Bond Brothers";
alert(jewelThieves);
</script>
When you save your file and refresh your Well done! You’ve
ou’ve
page, you will see your text displayed in just written yyour
an alert. cript
first JavaScript
programs!!
71
IF STATEMENTS
If statements are a way of telling our browser to perform an instruction only if the condition of our variable
is true. If the condition of our variable is false, our browser won’t perform the instruction in the code.
We have to structure if statements in a certain way. We start them with the statement keyword (if). Then
we open a pair of brackets and put the rule for our if statement inside them. Then we open a pair of curly
braces ({ }). Inside them we put the instruction we want to happen only when our if statement is true.
Let’s have a look at an example where
Equal to operator
we’ve used the equal to operator (==)
to create an if statement. Here the value <script> Curly brace
of our variable is set to Dr Day using the var person = "Dr Day";
assignment operator (=). We then create an if(person == "Dr Day") {
if statement by asking our browser to check If alert("Hello Dr Day!");
if the value in our variable is equal to (==) statement }
Dr Day. Then we ask our browser to pop up </script>
Alert
an alert if our condition is true.
72
<script>
var person = "Ernest";
if(person == "Dr Day") {
alert("Hello Dr Day!");
}
</script>
operator
<script>
var diamondCarats = 300;
if(diamondCarats > 299) {
Valuable Diamond Alert!
alert("Valuable Diamond Alert!");
}
</script> OK
Using if statements in your JavaScript code means you can build more
complex programs that change according to the value in a variable.
Let’s build a program that uses an if statement.
1. Open up your text-editing program. 2. Create an if statement using the equal to operator (==).
Create a new HTML file called Make an alert pop up if the condition of a variable is true.
ifstatements.html. Type this code First, create a variable called dogName between your
into your new file: <script> tags. Then create your if statement and alert.
Don’t forget to put the instruction for the if statement st
<!DOCTYPE html> in brackets and the instruction for your alert in curly
<html> braces ({ }). Your code will look like this:
<head>
<title>Conditionals</title> <script>
</head> var dogName = "Ernest";
<body> if(dogName == "Ernest") {
<script> alert("You discovered the Monk Diamond!");
</script> }
</body> </script>
Conditionals
OK
<script>
var name = "Tony Twinkles";
if(name == "Dr Day") {
Conditionals
Else alert("Access Granted!");
statement }
else {
alert("Access Denied!");
} Access Denied!
</script>
OK
75
75
1. Open up your text-editing program. Create 3. Now add an else statement after your if
a new HTML file called elsestatements.html. statement. This statement will run if the condition
Then copy and paste your code from of the if statement is false. Your code will look
ifstatements.html into your new file. like this:
Modify the code so that it looks like this:
<script>
<!DOCTYPE html> var diamondValue = 10;
<html> if(diamondValue <= 9.9) {
<head> alert("Value: Under £10 million!");
<title>Conditionals</title> }
</head> else {
<body> alert("Value: Over £10 million!");
<script> }
</script> </script>
</body>
2. Create a new if statement in your <script> 4. Save your HTML file and open it in your
block using the less than or equal to operator browser. Your else statement will run
(<=) . Make the condition of your if statement and an alert will pop up.
false. Your code will look like this:
Conditionals
<script>
var diamondValue = 10;
if(diamondValue <= 9.9) {
Value: Over £10 million!
alert("Value: Under £10 million!");
}
</script> OK
76
WRITING JAVASCRIPT
JavaScript always has to be written inside the <script> tag, so that your browser
knows you are switching from HTML to a new programming language. You can put
<script> tags in the <head> or <body> of your page.
Just like HTML and CSS, JavaScript is written in a special way and has its own syntax.
It is a case-sensitive language. You should leave spaces between pieces of code to
make them easier to read.
Each instruction you give your browser in JavaScript is called a statement. Statements
have to end in a semi-colon (;). Curly braces ({ }) are used to group statements
together into a block of code to be run in one go by your browser.
Statements normally start with a keyword that tells you the action the statement
will perform.
You can store information in your browser using variables. Variables have a name and
a value, which can be either text or numbers. If the value is text it has to be in double
quotes (" "). If your variable name has two words, write it using camelCase.
To change or set the values of your variables you can use assignment
operators, arithmetic operators and comparison operators.
If statements and else statements are known
as conditional statements.
Using conditional statements Using JavaScript helps
allows us to make our code do us make interactive web
different things depending on pages that respond to
the value of a variable. the user.
77
<script>
Function function sayPassword() {
keyword alert("Password!");
} Password!
sayPassword(); Statement
</script> OK
Function call
Functions always have to be written in the same way. Each part is an important instruction for your browser.
A function needs:
The function keyword
To define and create a function you have to use the function keyword.
A function name
Then you need to give your function a name. The name should be short and explain
the action the function performs. The name always ends with a pair of brackets.
Curly braces
After the function name you have to open a pair of curly braces ({ }). All the statements
you want to group together in the function have to go inside the curly braces.
Statements
Statements form the body of your function. You can use as many statements as you
want and the block of code will run in your browser whenever you call the function.
A function call
To call our function and run the block of code, you have to type the name of the
function (including the brackets) followed by a semi-colon. After you have defined
your function, you can call your function anywhere in your <script> block.
78
You can pass arguments to any kind of function. You might have wondered why function names
and function calls always end with a pair of brackets. It’s so you can pass the function an
argument. Turn over to see how to do it.
79
In this piece of code we have created a function that will pop up an alert. We do this by adding an
argument to our function. This kind of argument is called a parameter. We then code an alert which tells
our browser to pop up some text plus the argument. We then tell the browser the name to insert in the alert
by putting it in the function call.
Functions will often In this example we’ve created a function called getName.
perform an action and We want our function to give us Dr Day’s name as a value, so
rreturn the result to the we’ve used a return statement and set her name as the value.
rest of your code. We’ve then stored the function name as the variable value. When
the alert pops up, it will pop up with the value of the return.
80
</body>
</html>
Restricted access!
3. Save your HTML file and open it in
your browser. An alert will pop up.
OK
81
<!DOCTYPE html>
<html>
<head>
<title>Diamond Colour</title>
</head> Value set to
Onclick attribute JavaScript
<body>
<p onclick="alert('Green');">
Click here to find out the colour of the Monk Diamond
</p>
</body>
</html>
82
Did you
notice?
Diamond
mond co
83
<body>
<a href="monkdiamonddiscovery.html">
Click here to visit the Monk Diamond web page
</a>
</body>
Then you add the onclick attribute and the return statement. Set the value of the return statement to “false“,
like this:
Return statement False value
<body>
<a href="monkdiamonddiscovery.html" onclick="return false;">
Click here to visit the Monk Diamond web page
</a>
</body>
84
Practise using the HTML onclick attribute to run a piece of JavaScript code.
Knowing how to do this will mean you can make HTML elements respond to
the user.
1. Open up your text-editing program. Create 2. In your <body> create a hyperlink that will take
a new HTML file called onclick.html. your user to Google. Use the anchor <a> tag
Type this code into your new file: and href attribute. Set the value to the Google
URL. Your code will look like this:
<!DOCTYPE html>
<html> <body>
<head> <a href="https://www.google.com">
<title>Onclick</title> Google
</head> </a>
<body> </body>
</body>
</html>
3. Now add your onclick attribute to your opening <a> tag. Set the value of your onclick to a JavaScript
alert. Remember to use single quotes (' ') for the alert argument. Your code will look like this:
4. Save your HTML file and open it in your browser. When you click on the link an alert will
pop up. When you click OK, you will be taken to Google.
85
<!DOCTYPE html>
<html>
<head>
<title>Password</title> Don’t forget the
<style> top secret password
body {
is Ernest300
Ernest300.
CSS class
background-color: lightblue;
padding: 30px;
}
</style>
</head>
<body>
<p style="font-size: 30pt;">THE MONK DIAMOND DISCOVERY</p>
<p>Please enter the password to view this website.</p>
<p>Password:</p>
<a href="monkdiamonddiscovery.html"> Hyperlink
Click here to submit password and view website
</a>
</body> Password
</html>
Here we’ve created a simple web page using THE MONK DIAMOND DISCOVERY
HTML and CSS. We’ve included a hyperlink
that links to our Monk Diamond Discovery Please enter the password to view this website.
web page. But there isn’t anywhere on our Password:
page where the user can enter their password.
We need to create a box so that the user can Click here to submit password and view website
type it in.
86
<body>
<p style="font-size: 30pt;">THE MONK DIAMOND DISCOVERY</p>
<p>Please enter the password to view this website.</p>
<p>Password:<input id="passwordBox" type="text"/></p>
<a href="monkdiamonddiscovery.html"> Type attribute
Click here to submit password and view website
</a>
</body> Id attribute
87
<body>
<p style="font-size: 30pt;">THE MONK DIAMOND DISCOVERY</p>
<p>Please enter the password to view this website.</p>
<p>Password:<input id="passwordBox" type="password"/></p>
<a href="monkdiamonddiscovery.html">
Click here to submit password and view website Password value
</a>
</body>
Password
88
<script> getElementById
Variable 1 function checkPassword() {
var password = document.getElementById("passwordBox");
Variable 2 var passwordEntered = password.value;
} Id attribute
</script>
In our first variable we are using a new built-in function called getElementById. You will learn all about this
function and use it more in Mission 3. It is a handy function that finds the HTML element with the specified
id attribute. The id attribute we have selected here is for our <input/> tag. So the value of our variable
will be whatever data the user has typed into the password box.
We then create a second variable to store the data that the user has typed into the password
box. We create this value by typing the name of our first variable followed by a dot (.)
then the value keyword. We do this so we can write an if statement using the value
of this variable.
We now need to create an if statement. If the
condition of our second variable is true and our
Turn the page to
password text is equal to (==) Ernest300, the
see what that code
hyperlink will work. If the condition of our variable is looks like!
false and the password text is not equal to Ernest300,
the link won’t work and an alert will pop up. We don’t need to use
an else statement because the return statement will halt the function.
89
<script>
function checkPassword() {
var password = document.getElementById("passwordBox");
If statement var passwordText = password.value;
if(passwordText == "Ernest300") {
return true;
}
alert("Access denied! Incorrect password!");
Alert
return false;
}
</script>
Finally we have to make our JavaScript work with our HTML elements. We need to look at the code in
the <body> of our page now. We want to call the checkPassword function when someone clicks on the
hyperlink in our page. So we need to add an onclick attribute to our opening <a> tag, like this:
<body>
<p style="font-size: 30pt;">THE MONK DIAMOND DISCOVERY</p>
<p>Please enter the password to view this website.</p>
Function call
<p>Password:<input id="passwordBox" type="password"/></p>
<a href="monkdiamonddiscovery.html" onclick="return checkPassword();">
Click here to submit password and view website
</a> Password
</body>
rd
passwo Click here to submit password and view website
The Monk
THE MONK DIAMOND DISCOVERY
The jewel was stolen three years ago from the House of Volkov.
The prime suspects in the theft were the Bond Brothers.
The team thinks the diamond had been hidden by the thieves.
They sent this photo from their camp:
The Monk Diamond
Fact File
Carats: 300
Colour: Green
Value Over £10 million
90
2 CREATE A PASSWORD
It’s time to have a go at using all the JavaScript Code Skills you’ve learnt in this
mission to create a new web page that asks the user to enter a password. This
web page will protect the web page you built in Mission 1. If the user gets the
password right, they will be able to access the Monk Diamond Discovery web
page. If they get it wrong, an alert will pop up telling them that access is denied.
When you build your new web page make sure you code these things using HTML
and JavaScript:
91
92
Password: •••••••••
B
Brilliant coding! This password
pag
g will keep the Monk Diamond
page
s
safe. Don't forget you can use
m CSS properties to change
more
the look of the page.
93
Dear Coder,
To-Do List
• Commission a state-of-the-art
unbreakable glass display case
• Order a new velvet cushion for
the diamond
• Hire private security
• Hire a bodyguard to protect
Mr Volkov
• Invite guests
• Buy diamond-themed snacks
and lemonade
• Buy dog biscuits for Ernest
jeweller of the Imperial Court, supplying the Russian nobility with beautiful jewellery
in intricate designs. The House of Volkov
Today the House of Volkov is located on one of the most exclusive streets in
Moscow, near to St Basil’s Cathedral. Volkov diamonds are still renowned for their
quality and are some of the most expensive in the world.
Viktor Volkov, the current owner, bought the Monk Diamond for an undisclosed sum
at auction. It was the centrepiece of the House of Volkov’s private collection. It was
displayed to the public in an antique glass case until it was stolen in a smash-and- Industry: Jewellers
Founded: 1794
grab robbery. The theft of the Monk Diamond remains unsolved. Since the robbery
Founder: Vladimir Volkov
the House of Volkov has reported a sharp drop in sales and there are rumours that Headquarters: Moscow
it might be sold. Mr Volkov said in a recent interview, “I would be devastated if the Area served: Worldwide
business, which has been in my family for generations, had to close.”
Our app will have a text box that Professor Bairstone can type into. When he clicks on the button, the item
will be added to the list. When he’s completed a task, he can click on it and it will be removed. We can
code all these things using the JavaScript you learnt in Mission 2 with some new programming tools.
98
99
Let’s start making the app for Professor Bairstone by building a button.
Use <input/> tags to code a text box and button.
<body>
<p>Special Exhibition To-Do List</p>
<br/>
<input type="text" value="Type here to add task"/>
<br/>
<input type="button" value="Add item"/>
<br/>
</body> To-Do List A
100
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title> JavaScript
<script> function
function addItem() { Please don't
alert("Remember dog biscuits!"); forget my
} rations!
Alert
</script>
</head>
<body>
<p>Special Exhibition To-Do List</p>
<br/> Function
<input type="text" value="Type here to add task"/> name
Input tag <br/>
<input type="button" value="Add item" onclick="addItem();"/>
<br/> Onclick
</body> Button attribute
</html> To-Do List
101
Now practise using the onclick attribute to make a button that pops up an alert.
1. Open up your text-editing program. Create a new HTML file called button.html. Then copy and paste
your code from app.html into your new file. In your <body> add an onclick attribute that calls
a JavaScript function to your button, like this:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title>
</head>
<body>
<p>Special Exhibition To-Do List App</p>
<br/>
<input type="text" value="Type here to add task"/>
<br/>
<input type="button" value="Add item" onclick="addItem();"/>
<br/>
</body>
</html>
</script>
</head>
Special Exhibition To-Do List
3. Save your HTML file and
Type here to Hire security team!
add task
open it in your browser.
Add item
Your button will now pop OK
102
Programming interfaces
The DOM is an application program interface The alert function we used in Mission 2 is a
(or API). APIs help when you are coding. They built-in function. Rather than having to code an
are sets of built-in functions that you can easily use alert, we can just type the alert keyword and our
with your HTML and browser knows what to do. The DOM works in a
JavaScript code. very similar way. We can use the DOM’s built-in
functions to make changes to our HTML document
after it’s been drawn on-screen.
The DOM will Using the DOM lets us build web pages that
help make your change and react when the user does something.
app interactive. So if we want our to-do list to be interactive and
change on-screen when Professor Bairstone adds
a new task or checks one off, we need to use the
DOM’s methods and properties.
WORD APPLICATION PROGRAM INTERFACES (APIS) save lots of time when you are writing code,
CODE
because they allow you to use their built-in functions. Rather than having to write the
code for these functions yourself, you can use the API’s functions in your code. There are
APIs to do all sorts of things, from storing information to adding content to your page.
103
Before you can use any of the DOM’s built-in document. Dot
functions, you have to tell your browser you want
to access the API. To do this you always have to DOM keyword
type this piece of code at the start of an instruction
for the DOM.
Once you’ve told your browser you want to use the DOM, you then have to say which DOM functions
you want to use. The DOM has built-in functions called methods and properties that allow you to change
HTML elements. A method is an action you can do, such as adding or removing a HTML element. A property
is a value that you can access and change, such as setting the contents of a HTML element to a piece of text.
When you want to use a method or property, you separate the DOM keyword from the DOM method
or property with a dot (.). Because the DOM lets you access any HTML element in your web page, lots of
DOM methods have the word “element” in them. In Mission 2 you used a DOM method with JavaScript
when you wrote this code:
document.getElementById("password");
Did you
Id attribute
notice?
DOM keyword Dot DOM method
When we use dots (.) to separate
Here we are telling our browser to use the DOM. pieces of code we are using dot
Then we are asking to use a DOM method called notation. The dot tells your browser
getElementById to find a HTML element. Finally, you will be using DOM methods
we’re directing our browser to find the HTML and properties.
element with that specific id attribute.
104
You can use the DOM’s innerHTML property to access or change the contents of a HTML element
in your app. You can then use the contents of the HTML element as a value in your JavaScript code.
HTML element
Variable
105
<!DOCTYPE html>
<html>
<head>
<title>List Alert</title>
</head>
Id attribute
<body>
<div id="list">Buy Ernest a new collar</div>
<script>
var showList = document.getElementById("list");
alert(showList.innerHTML);
</script> getElementById
</body> innerHTML method
</html> property
Pawsome
list!
106
<script>
function addItem() {
document.getElementById("container").innerHTML = "Item to remember";
}
</script>
3. Then make your button call your JavaScript function when it is clicked. Add the onclick attribute to
your <input/> tag and set the value of the onclick attribute to the name of your function, like this:
107
108
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title>
</head>
Id attribute
<body>
createElement
<div id="list">To-Do List</div>
<script>
Variable Create <div>
var newItem = document.createElement("div");
newItem.innerHTML = "Item added to list";
document.getElementById("list").appendChild(newItem);
</script>
Add HTML
</body> appendChild element
</html>
To-Do List
109
Now it’s your turn to have a go at using the createElement and appendChild
methods. In your code, use the DOM and JavaScript to create a new HTML
element when an existing element is clicked. Using APIs like the DOM makes
building apps easier.
1. Open up your text-editing <!DOCTYPE html>
program. Create a new HTML <html>
file called newelements.html. <head>
Code a <div> (with an id <title>New Elements</title>
attribute) that contains text, </head>
like this: <body>
<div id="list">Click here to add item</div>
</body>
</html>
110
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = "New item";
document.getElementById("list").appendChild(newItem);
}
</script>
5. Now the only thing missing is the function call in the <body> of our code. Add the onclick attribute to
the <div> in your <body>, so that when the <div> text is clicked your addItem function is called. Your
code will look like this:
<body>
<div id="list" onclick="addItem();">Click here to add item</div>
</body>
New Elemen
Turn over to
find out!
111
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title>
</head>
<body>
<p>Special Exhibition To-Do List</p>
<br/>
<input type="text" value="Type here to add task"/> Text box
<br/>
<input type="button" value="Add item"/> Button
<br/>
</body>
</html>
To-Do List A
112
Now let’s create a function in our <head> that will set the text inside our newItem variable. Finally we
run when the onclick is clicked. Our function needs need to use getElementById to find the <div> with
to use the createElement method to make a new the id attribute “list“ in our body. Then we can use
<div>. This new <div> will be stored in a variable appendChild to add our newItem to our list. Our
called newItem. Then we need to use innerHTML to <script> block in our <head> will look like this:
<script>
Create new <div>
function addItem() {
Set var newItem = document.createElement("div");
innerHTML of newItem.innerHTML = "New item";
new <div>
document.getElementById("list").appendChild(newItem);
} Add new <div> to
</script> Find id attribute <div> in <body>
To-Do List A
When we run this code in our browser the
button works. The text “New item” is added
to the list every time the button is clicked.
Special Exhibition To-Do List
113
We’re then going to change our JavaScript in the <head> so that it sets the innerHTML of the new <div>
to whatever value has been typed into the text box. To do that we have to use getElementById to find the
text box using the id attribute. We then access the value by making this change to our <script> block:
<script>
function addItem() { Id attribute
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
document.getElementById("list").appendChild(newItem);
} Access value
</script>
114
115
Let’s build a basic app. The app should have a text box and a button that Professor
Bairstone can use to add his tasks to the list. Use the DOM and JavaScript so that
when the button is clicked the task in the box will be added to the list.
1. Open up your text-editing program. Create a new HTML file called basicapp.html. Then copy and
paste your code from app.html into your new file. Modify your code so that the text box has an id
attribute of your choice, like this:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title>
Don’t forget
</head> to set the id
<body> attribute!
<p>Special Exhibition To-Do List</p>
<br/>
<input type="text" id="box" value="Type here to add task"/>
<br/>
<input type="button" value="Add item"/>
<br/>
</body>
</html>
3. Now add an onclick attribute to your button <input/> tag. Set your onclick to call a JavaScript
function. Your code will look like this:
116
5. Now use the DOM to code a function called addItem that will create a new <div> when the button is
clicked. The function will then use innerHTML to set the value of the <div> to the value in the text box.
Finally the function will use appendChild to add the new HTML element to the <div> in your <body>.
Your code will look like this:
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
document.getElementById("list").appendChild(newItem);
}
</script>
s
biscuit
dog
117
The removeChild method does the opposite to the appendChild method. Rather than adding a HTML
element to another HTML element, it takes away a HTML element from another HTML element. You use it
just like appendChild. Select the HTML element you want to remove using the id attribute and then tell your
browser to remove it, like this:
document.getElementById("list").removeChild(this);
As you know already, HTML tags can be nested In the document object all elements are connected,
inside other HTML tags. When you like in a family tree. Any HTML element that is inside
use the removeChild method, another is called a child of that element. The HTML
you remove the HTML element element on the outside is called the parent. When
inside the HTML element you you use removeChild, you remove the child HTML
selected using the id attribute. element from the parent HTML element.
When you use the removeChild method you also
have to use a handy JavaScript keyword called
These new pieces “this“. The this keyword points to whichever HTML
of code are making element was used to call the function. Let’s take a
our app more and look at an example:
more interactive.
118
Things To
In this example, the first <div>, with the id attribute
“list“, is the parent element. The <div> nested
inside it, with the woolly socks text, is the child
Velvet cushion for diamond
element. When we click on the woolly socks text,
we’re using getElementById to find the <div> Woolly socks
called list.
Then we’re using the removeChild method
and the this keyword to remove this piece of text.
Just like we learnt in Mission 2, we have to pass
an argument for our function to work. We use
Things To
the argument “item“ and the “this“ keyword to
keep track of the HTML element we are trying
to remove. Professor Bairstone can now remove
things from the list by clicking on them. Velvet cushion for diamond
Silly Professor
Bairstone!
119
Let’s have a go at using the removeChild method and this keyword to remove
a HTML element.
<script>
function removeItem(item) {
document.getElementById("list").removeChild(item);
}
</script>
3. Finally add an onclick attribute to the child 4. Save your HTML file and open it
<div>, so that when the text inside it is clicked, in your browser. When you click on
it will be removed from the list. The onclick the second item, it will vanish from
should call your function and use the this the screen.
keyword, like this:
<div onclick="removeItem(this);">
Woolly socks
</div>
120
<!DOCTYPE html>
<html> We need to get all
<head> these tasks checked
<title>To-Do List App</title> off the list!
<script>
function addItem() {
var newItem = document.createElement("div");
Onclick newItem.innerHTML = document.getElementById("box").value;
attribute set
newItem.onclick = removeItem;
document.getElementById("list").appendChild(newItem);
}
function removeItem() {
document.getElementById("list").removeChild(this);
}
</script> removeItem
</head> function called
<body>
<p>Special Exhibition To-Do List</p>
<input type="text" id="box" value="Type here to add task"/>
<br/>
<input type="button" value="Add item" onclick="addItem();"/>
<div id="list"></div>
</body>
</html>
In this example, we’ve created a new <div> using createElement. We’ve stored the <div> in a variable so
we can set its innerHTML to whatever item has been typed into the text box. We then use the DOM to set
the onclick attribute of the new item. When this item is clicked, it will call the removeItem function and the
item will be removed from the list.
121
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title>
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
document.getElementById("list").appendChild(newItem);
}
</script>
</head>
<body>
<p>Special Exhibition To-Do List</p>
<br/>
<input type="text" id="box" value="Type here to add task"/>
<br/>
<input type="button" value="Add item" onclick="addItem();"/>
<br/>
<div id="list"></div>
</body>
</html>
122
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
newItem.onclick = removeItem;
document.getElementById("list").appendChild(newItem);
}
</script>
3. Code a second function in your <script> block called removeItem. The function needs to use
getElementById to find the <div> in your <body>. Then it should use removeChild and the this
keyword to remove any item the function calls. Type out this function so your <script> block
now looks like this:
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
newItem.onclick = removeItem;
document.getElementById("list").appendChild(newItem);
}
function removeItem() {
document.getElementById("list").removeChild(this);
}
</script>
123
4. Your finished code block for your app will look like this:
<!DOCTYPE html>
<html> This special
<head> exhibition is going
<title>To-Do List App</title> to be a blast!
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
newItem.onclick = removeItem;
document.getElementById("list").appendChild(newItem);
}
function removeItem() {
document.getElementById("list").removeChild(this);
}
</script>
</head>
<body>
<p>Special Exhibition To-Do List</p>
<br/>
<input type="text" id="box" value="Type here to add task"/>
<br/>
<input type="button" value="Add item" onclick="addItem();"/>
<br/>
<div id="list"></div> To-Do Li To-Do Li
</body>
</html> Special Exhibition To-Do List Special Exhibition To-Do List
124
125
<!DOCTYPE html>
<html>
<head>
<title>Storage</title>
</head>
<body>
<input type="text" id="box" value="Type here to add task"/><br/>
<input type="button" id="save" value="Save" onclick="save();"/><br/>
<input type="button" id="load" value="Load" onclick="load();"/><br/>
Saved item: <div id="savedList"></div>
</body>
</html>
2. Now code a function in your <head> that uses localStorage to save the value typed into the text box in
your browser. Don’t forget to use camelCase when you write the localStorage keyword. Your code will
look like this:
<script>
function save() {
var newItem = document.getElementById("box").value;
localStorage.box = newItem;
}
</script> Don't forget to use
Google Chrome or
Mozilla Firefox for
this exercise.
126
<script>
function save() {
var newItem = document.getElementById("box").value;
localStorage.box = newItem;
}
function load() {
var savedDiv = document.getElementById("savedList");
savedDiv.innerHTML = localStorage.box;
}
</script>
5. Now click Load. The value you typed into the text box will appear on-screen. Then refresh your page.
The item will disappear from your screen. But when you press Load, the text you saved using
localStorage will be loaded in your browser.
Storage Now that
is useful!
Invite guests
Save
Load Storage
Saved item:
127
<!DOCTYPE html>
<html>
<head>
<title>To-Do List App</title>
<script>
function addItem() {
var newItem = document.createElement("div");
newItem.innerHTML = document.getElementById("box").value;
newItem.onclick = removeItem;
document.getElementById("list").appendChild(newItem);
saveList();
Save list function call
}
function removeItem() {
document.getElementById("list").removeChild(this);
Save list saveList(); List saved to
Save list function call
function } localStorage
function saveList() {
localStorage.storedList = document.getElementById("list").innerHTML;
Load list }
function function loadList() {
document.getElementById("list").innerHTML = localStorage.storedList;
}
</script>
</head>
<body>
<p>Special Exhibition To-Do List</p>
<input type="text" id="box" value="Type here to add task"/>
<br/>
<input type="button" value="Add item" onclick="addItem();"/>
<div id="list"></div>
</body>
</html>
128
To save the list we need to create a new saveList to get the contents of the <div>. Everything in our
function that will save it using localStorage. To do <div> will now be saved in localStorage.
this, we have to choose a variable name to assign We want to save our list every time an item is
the information we want to store in localStorage. added or removed, so we also need to make sure
We then use getElementById to find the <div> in the addItem and removeItem functions call the
the <body> of our page. Finally we use innerHTML saveList function after they have run.
To load the list we need to create a second function. Whenever the loadList function is called, it will set
the innerHTML of the <div> with the id “list“ to whatever has been saved in localStorage.
We need to call our loadList function so that when our browser finishes loading, it loads our list too.
To make sure we don’t try to load a list that hasn’t been saved, we have to use an if statement before we
try to use localStorage. The if statement we need looks like this:
To-Do List A
129
function loadList() {
Code that document.getElementById("list").innerHTML = localStorage.storedList;
starts the for(var i = 0; i < list.children.length; i++) {
loop list.children[i].onclick = removeItem;
} Condition
} Code to run for loop
in loop
removeItem function on every item that we load SJavaScript that runs the same
from localStorage. It counts up through each new piece of code again and again.
HTML element that we’ve added to our to-do list Programmers use them so they don’t
and sets the onclick attribute for each new element. have to type the same piece of code over
You will learn more about loops in Mission 5, and over.
but for now you should know that loops are split
into three parts.
A loop needs:
That's very
The code that starts the loop clever coding!
The condition to check if the loop
is allowed to run
Code that runs every time the
loop runs.
130
When you code your app use HTML and JavaScript and the new APIs.
Make sure you include these things:
Don't forget to
Turn over to see use the Get Coding!
the entire code website if you
block you need need help.
for your app !
131
132
<script>
if(localStorage.storedList) {
loadList();
}
The House of Volkov
</script>
</body>
</html> Special Exhibition To-Do List
Dog biscuits
Add item
133
Dear Coder,
Dear Coder,
Interpol know that the gang has three core members, who are known only by their aliases: Light Fingers,
Gemma the Gem and Tony Twinkles. The three members are aided by other smaller crooks, who help them
choose their targets, make their escapes and hide the stolen jewels.
One of the gang is a skilled cyber-criminal, with access to government databases. In all their robberies the CCTV
cameras in the area surrounding the target are disabled during the period of the crime.
As well as stealing from expensive boutiques in smash-and-grab raids, the Bond Brothers have held up courier
vans or motorcycles delivering jewellery. They have disguised themselves as road workers and then used fake
road signs to direct the drivers into dead-end roads, before robbing them.
Their success seems to be due to the way they vary their tactics. No raid is ever the same, making it very hard
for the authorities to predict what they will do next.
CODE
that has the map we need. Programmers call this
S
content is inserted into
integrating one web page with another.
an existing web page, we
When we want to integrate our web page with
say it has been EMBEDDED
another website, we have to write some code that
in the page. The embedded content
will connect our page to the web server that stores
becomes part of the page.
the other website. We can then access the data and
content on that server that we need.
Web APIs
You already know what an API is and have You can use web APIs for lots of different things
used two of them in Mission 3: the DOM and when you’re building a website. You might have
localStorage APIs. Those APIs let you access some come across some of these web APIs on websites,
handy built-in functions. APIs come in all shapes which help you do these things:
and sizes and the API that we need to embed a
map in this mission is slightly different to those we Add maps
have used already.
APIs used to integrate with other websites are Add Like or Share buttons for
sometimes called “web APIs” or “web services”. Facebook
They let you access a website’s built-in features and
Share videos on YouTube and Twitch
functions, so you can add extra content to your
page without having to write lots of code.
138
https://developers.google.com/maps/documentation/embed/
Did you
know?
You need a Google account to get a Google
Maps API key. You have to be over 13 years old
to have a Google account. If you are under 13, Turn over to find
ask an adult if you can use their account with
out how to get your
their supervision, or if they can sign up on your
behalf. Make sure you, or the adult helping you,
own API key.
have read the terms and conditions. Go to
www.support.google.com to find out more.
139
Google and the Google logo are registered trademarks of Google Inc., used with permission.
https://developers.google.com/maps/documentation/embed/
Google Maps
Google Maps
140
Google and the Google logo are registered trademarks of Google Inc., used with permission.
6. Your API key will be displayed. It will
be a long code made up of numbers
and letters. They are all unique but it
will look a bit like this:
Google Maps
141
<!DOCTYPE html>
<html>
<head>
<title>Diamond Discovery</title>
</head> Source attribute
<body>
<iframe> <iframe src="https://www.monkdiamonddiscovery.com">
</iframe>
</body> URL
</html>
Diamond
Fact File
Carats: 300
Colour: Green
Value Over £10 million
appearance of the embedded page. Let’s take a look at all the
attributes you can use:
142
Now let’s see how we can use all these attributes to change the appearance of our <iframe> and
embedded content. Remember you always have to add attributes inside your opening tag, like this:
Diamond
<!DOCTYPE html>
<html>
The Monk Diamond Discovery
vee
<head>
<title>Diamond Discovery</title> Stolen Diamond Discovered in Siberia!!
</head> They have discovered the Monk Diamond in a remote cave in Siberia.
Professor Bairstone's dog, Ernest, sniffed out the diamond.
The jewel was stolen three years ago from the House of Volkov.
The prime suspects in the theft were the Bond Brothers.
<body> The team thinks the diamond had been hidden by the thieves.
They sent this photo from their camp:
<iframe V
Fact File
Carats: 300
Colour: Green
Value Over £10 million
width="350px" Frameborder
attribute
Height height="350px"
attribute frameborder="0px" Here we’ve set the width and height
Style attribute
style="border: 0px" attributes to the same number of
src="https://www.monkdiamonddiscovery.com"> pixels to make our <iframe> into
</iframe> a square. The frameborder attribute
</body> and the CSS border property have
</html> both been set to 0 pixels. This is so
the <iframe> will blend into the
Useful thing, this page. You normally do this with an
<iframe> tag!
<iframe>, so that the embedded
content looks like it is part of
your page.
143
Now you’ve read about the <iframe> tag and how it works, let’s have a go
at using the tag and its attributes to change the way a piece of embedded
content displays in a web page.
1. Open up your text-editing program. Create a 3. Finally add the source attribute. Set its value to
new HTML file called iframe.html. Add the the URL of your favourite website, like this:
opening and closing <iframe> tags to the
<body> of your page, so the code in your new <iframe
file looks like this: width="350px"
height="350px"
<!DOCTYPE html> frameborder="0px"
<html> style="border: 0px"
<head> src="https://www.bing.com">
<title>iFrames</title> </iframe>
</head>
<body> 4. Save your HTML file and open it in your
<iframe> browser. Your chosen site will be
</iframe> embedded in your web page.
</body> Now try changing the height and
</html> width of your <iframe> and seeing what
it does to the embedded content.
2. Now set the attributes of your <iframe>. Include
the width, height, frameborder and style attribute
inside your opening <iframe> tag, like this:
<body>
<iframe I really like this
width="350px" way of embedding
height="350px" new content in
frameborder="0px" our page.
style="border: 0px">
</iframe>
</body>
144
URLs
The Google Maps Embed API needs you to provide it with a URL in the source attribute of your
<iframe>. The URL has to contain several important pieces of information so the correct map is
embedded. Let’s have a look at exactly what information we need to include in a URL if we want
to embed a map of Moscow in our web page: API key
https://www.google.com/maps/embed/v1/search?q=Moscow&key=API-KEY
Maps Embed API. You then have to tell that API in the form of a sequence of
what built-in function you want to use. We want to characters. Strings can be made
use the search API function on the Google server, up of words and numbers.
so we add that to the URL. The next piece of A PARAMETER is another name for a piece of
information is the specific part of our request, information, or an argument, that is passed
called the query string parameters. to a function so it can perform an action.
string parameters
The string parameters are the parts of a URL that in a certain way, so the Google server is able to
contain variables – the pieces of information that access information stored in our variables. The two
depend on the user. In our example there are two parts of the query string parameters are the key
parameters. The two variables are the map we are and the value. You need both of these parts for
searching for (Moscow) and our unique API key. your parameters to work. Turn over to see the URL
We have to structure our query string parameters for the map of Moscow.
145
In this URL the two parameters are separated by an ampersand (&). The first is the query key and the
second is the API key. Your browser needs them both because they contain this important information:
<!DOCTYPE html>
<html>
<head>
<title>Moscow</title>
</head>
<body>
<iframe
width="450px"
height="450px"
frameborder="0px"
style="border: 0px"
src="https://www.google.com/maps/embed/v1/search?q=Moscow&key=API-KEY">
</iframe>
</body>
</html>
146
Let’s embed a Google Map for Moscow in a page. It’s an important skill to
master before we plan our route for Dr Day and the head of security.
1. Open up your text-editing program. Create a 2. Now add the width, height, frameborder and
new HTML file called citymap.html. Then copy style attributes inside your opening <iframe>
and paste your code from iframe.html into tag. Set the values, like this:
your new file. Modify it so that it looks like this:
<body>
<!DOCTYPE html> <iframe
<html> width="450px"
<head> height="450px"
<title>City Map</title> frameborder="0px"
</head> style="border: 0px">
<body> </iframe>
<iframe> </body>
</iframe>
</body>
</html>
3. Add the source attribute inside your opening <iframe> tag. Use the Google Maps Embed API URL and
add the two parameters. Set the parameter “q“ to the location you want for your map and the parameter
“key“ to your unique API key that you got earlier in the mission. Your source attribute will look like this:
city Map
<iframe
width="450px"
height="450px"
frameborder="0px"
style="border: 0px"
src="https://www.google.com/maps/embed/
v1/search?q=Moscow&key=API-KEY">
</iframe>
147
Like before, the first part of our URL is the path to the Google Maps Embed API. We then request to use
the directions API function. Then we use three parameters: the origin, destination and API key. For the
origin and destination you can put lots of different values, but the simplest thing to do is put the place
name followed by the city name. These two new keys are important for your browser as they provide the
following information:
Did you
notice?
We’ve included the name of the I can't wait to
site and the city, separated by a see St Basil's
comma (,). There is no space after Cathedral!
the comma.
148
<!DOCTYPE html>
<html>
<head>
<title>Top Secret Route</title>
</head>
<body>
<iframe
width="650px"
height="650px"
frameborder="0px"
style="border: 0px"
src="https://www.google.com/maps/embed/v1/directions?
origin=GorkyPark,Moscow&destination=StBasil,Moscow&key=
API-KEY">
</iframe>
</body>
Top Secret
</html>
This is exactly
what Dr Day needs
to get the Monk
Diamond safely
to the House of
Volkov!
149
4 PLAN A ROUTE
Great work! You’ve learnt how to use a web API and Google Maps to embed
content in your page. Now use your new knowledge to plan a route through
Moscow, from Gorky Park to St Basil’s Cathedral. Having a route will help
Dr Day keep the Monk Diamond safe.
When you plan your route, use your new Code Skills to do the following things:
Use an API key: use the Google Maps Embed API to get an API key.
Create an <iframe>: use this new HTML tag so you can embed content
in your page.
Change the way your <iframe> displays: use attributes to change the
height, width and borders of your <iframe>.
Use the source attribute: embed a URL that will connect to the web API
you need.
Use the Google Maps Embed API: create a Google Map using the
Google API.
Use the built-in direction function: plot a route using this function.
Set query string parameters: give the destination function the origin and
destination for your route.
Save your file in your Coding folder and call it route.html.
150
151
Dear Coder,
T HE E XPLORER ’ S This is a private entry with restricted access. To view the public entry for the
ENCYCLOPEDIA House of Volkov click here.
The Guide to Every Adventure
Home page The House of Volkov’s Security Team is responsible for protecting the highly
Contents valuable jewels on display in the House of Volkov’s private collection.
Featured discoveries
Famous explorers Since the theft of the Monk Diamond, the jewels on display in the shop are kept in
Historical expeditions locked cases. The reinforced glass is 200 times stronger than normal glass.
If you click on th
e thief,
you gain 1 point
If you click on a
guest,
you lose 2 poin
ts
This happens 6
times in total
The aim of the g
ame is to spot
all 6 thieves an
d score 6 points
In light of the theft, the owner Viktor Volkov has trained his security team to be on the alert for any customers
behaving suspiciously. In the last year several petty crooks have been caught trying to unlock the display cases
with skeleton keys.
The special exhibition Mr Volkov is hosting for the Monk Diamond will be the most high-profile event ever held by
the House of Volkov. Mr Volkov decided to consult Professor Bairstone about the security strategy for the opening
night of the exhibition.
The Bond Brothers have used disguises in past robberies and Mr Volkov and Professor Bairstone are worried that
members of the gang, or their associates, might try to infiltrate the exhibition by posing as guests.
The agreed strategy is to use the method developed for museums in London by Professor Li. A computer game
with a simple set of rules has proved to be an effective way of sharpening the reaction times of members of a
security team.
The game needs to be built urgently so the team are properly trained before the opening of the special exhibition.
156
Great work!
157
158
Did you
notice?
Turn over to
You have to use milliseconds with the setTimeout function. practise using
There are 1,000 milliseconds in a second. To work out the the setTimeout
number of milliseconds you need, multiply the number of function!
seconds by 1,000. So if you wanted your function to be
called after 3 seconds, you would multiply 3 by 1,000.
159
JavaScript timers, such as the setTimeout function, are very useful for building
games. Let’s have a go at using the setTimeout function, so you know how it
works and can add it to your game later in the mission. Let’s code a program
that counts up a number every second.
1. Open up your text-editing program. <!DOCTYPE html>
Create a new HTML file called <html>
timers.html. Type out this code: <head>
<title>Timers</title>
</head>
<body>
<div id="number">
</div>
</body>
2. Now add the <script> tag to your </html>
<head>. Inside your <script> block create
a variable and set its value to 0 using the
assignment (=) operator, like this: <head>
<title>Timers</title>
<script>
3. Now create a function called updateCount. var count = 0;
Every time the function is called it will use the </script>
addition operator (+) to add 1 to the value </head>
of your variable. Then use getElementById
and innerHTML to find
your empty <div> and <script>
set the contents to the var count = 0;
variable. Your code will function updateCount() {
Add 1 Update screen
look like this: count = count + 1;
document.getElementById("number").innerHTML = count;
}
</script> Find <div>
160
5. Finally we have to add a timer that will call our function every second to our <script> block.
We need to use the setTimeout function. We have to pass the function name and the number of
milliseconds to the setTimeout function as arguments. Our <script> block will look like this:
<script>
var count = 0;
function updateCount() {
count = count + 1;
document.getElementById("number").innerHTML = count;
setTimeout(updateCount, 1000);
}
</script> Call updateCount
in 1 second
Save your HTML file and open it in your browser. You will see your timer in action. The setTimeout
function will call your updateCount function every second. The function will run and every second
1 will be added to the value of your variable. The number in your browser will update automatically.
Timers
Timers
21
161
<!DOCTYPE html>
<html>
<head> I wonder if I could sniff
<title>Security Game</title> out the Bond Brothers?
<style> I've got a very good nose.
#board {
border: 1px solid black;
background-color: gray;
height: 350px;
width: 650px;
}
</style>
</head>
<body>
<input type="button" value="Play" onclick="startGame()";/>
<div id="board">
</div>
<script>
function startGame() {
gameLoop(); Function call
Function }
function gameLoop() {
Alert
alert("Game over!");
setTimeout(gameLoop, 3000);
}
Timer
</script> Number of
milliseconds
</body>
</html>
162
163
1
2
3
Now let’s use CSS to change the design and 4
layout of our <div> tags. Let’s create a CSS class 5
6
called character that will make our <div> tags
square blue boxes. In your text-editing program,
add this new CSS class to the <style> tag in
your <head>. Your complete <style> block will
now look like this:
<!DOCTYPE html>
<html>
Did you
<head> notice?
<title>Security Game</title>
<style> We have used the float CSS property.
#board { This will make our <div> tags align
border: 1px solid black; with one another.
background-color: gray;
height: 350px;
width: 650px;
}
.character {
New CSS
class background-color: lightblue;
width: 120px;
height: 120px;
padding: 10px;
margin: 10px;
float: left;
}
</style>
</head>
164
<body>
<input type="button" value="Play" onclick="startGame()";/>
<div id="board">
<div class="character">1</div>
<div class="character">2</div>
<div class="character">3</div>
<div class="character">4</div>
<div class="character">5</div>
<div class="character">6</div>
</div> Class attribute
<script>
function startGame() {
gameLoop();
}
function gameLoop() {
It's starting to
alert("Game over!");
look more like a
setTimeout(gameLoop, 3000); game now!
}
</script>
</body>
</html>
1 2 3 4
Something's making
my nose itch.
5 6
165
166
Security Ga
The if statement checks how many times our
loop has run. If it is less than (<) 12 times, it
keeps running by calling setTimeout again.
If it is more than 12 times, the else statement Play
167
168
Try using the CSS display property to make HTML elements appear and
disappear on your screen. You’ll need this to make your characters display
correctly in your game.
1. Open up your text-editing program. Create a new HTML file called display.html. Type out the
code below, then save your HTML file and open it in your browser. Your page will look like this:
<html>
<head>
Security
<title>Display</title> Thief
</head> Guest
<body>
<div>Security</div>
<div>Thief</div>
<div>Guest</div>
</body>
</html>
169
170
I like using
loops!
171
Variable
function flashCharacters() {
var board = document.getElementById("board");
Variable var classToSet = "";
Empty string
if(peopleVisible) { Id attribute
If statement
classToSet = "character visible";
} CSS class name
CSS class name
Else else {
statement classToSet = "character hidden";
} Loop
for(var index = 0; index < 6; index++) {
board.children[index].className = classToSet;
}
} Class name method
172
This tells our browser that if the condition of our variable is true it should use value1, and if it is false use
value2. So we can rewrite the code in our function like this:
Add your new flashCharacters function with the simplified if and else statements to your <script>
block. Make sure your gameLoop function calls your new function too. Save your code and open it
in your browser. Every 3 seconds your blue boxes will appear and disappear on your screen.
Security G
Turn over to see what
our whole code block
Play now looks like!
1 2 3 4
Security G
5 6
Play
173
Check your code in your text-editing program. The code you need
for your game will look like the block below. You have to refresh your
page between each play of the game. Make any changes you need
and save your file.
<!DOCTYPE html>
<html>
<head>
<title>Security Game</title>
<style>
#board {
border: 1px solid black;
background-color: gray;
height: 350px;
width: 650px;
}
.character {
background-color: lightblue;
width: 120px;
height: 120px;
padding: 10px;
margin: 10px;
float: left;
}
.hidden {
display: none;
}
.visible {
display: block;
}
</style>
</head>
174
175
Then code the new createCharacters function before your flashCharacters function:
function createCharacters() {
var board = document.getElementById("board");
for(var index = 0; index < 6; index ++) {
board.children[index].innerHTML = "Guest";
} Security G
}
Play
This is very similar to the function we coded earlier to set the
Guest Guest Guest Guest
CSS class of each character <div>. But this time we’ve used
innerHTML, like we used in Mission 3, to set the value of each
of the characters to “Guest”. Guest Guest
Now we need to add some code to our createCharacters function that will randomly pick one of the 6
character <div> tags to be the thief, every time the game loop runs. We need to write code that will pick
a random number. There isn’t an easy way of picking a random number using JavaScript, so the next piece
of code you need is quite complicated. Carefully type this new code at the end of your createCharacters
function, so that it looks like this:
176
Here we are using a new API called the Math API. It works in exactly the same way as the DOM and
localStorage APIs that we used in Mission 3. Using the Math API lets you access handy maths functions
that have been built in to your web browser. To find a random number you have to do the following
calculation:
board.children[randomNumber–1].innerHTML = "Thief"
so we’ll only ever get the numbers 0, Guest Thief Guest Guest
1, 2, 3, 4 and 5.
Security G
Guest Guest
Play
Save your code. Your new
Guest Guest Guest Guest
createCharacter function will
have added a thief to your
game. Now when you press Play, every time your game loop Thief Guest
177
var loops = 0;
var peopleVisible = false;
var gameScore = 0;
Every time the player clicks on the thief, we need to add 1 point to their score. And to make sure the player
is paying attention, every time they click on a guest we should take away 2 points. To create our scoring
system we need to add an onclick to every character, every time our game loop runs. Add this new code
to your createCharacter function:
function createCharacters() {
var board = document.getElementById("board");
for(var index = 0; index < 6; index ++) {
board.children[index].innerHTML = "Guest";
board.children[index].onclick = function() {
Variable gameScore += –2;
} Onclick
} Operator
var randomNumber = Math.floor(Math.random() * 6) + 1;
board.children[randomNumber–1].innerHTML = "Thief";
Variable board.children[randomNumber–1].onclick = function() {
gameScore++;
} Onclick
} Operator
We’re using the onclick just like we did in Mission 3. When a guest or thief is created, an onclick is
added. We’re using two new arithmetic operators to change the value of our gameScore variable. If the
user clicks on a guest, the += operator means the value that follows is added to the value in the variable.
In this case, since the value that follows is –2, it means that 2 is subtracted from the gameScore value.
If the user clicks on a thief, the increment operator (++) means 1 is added to the value in the variable.
178
function gameLoop() {
peopleVisible = !peopleVisible;
createCharacters();
flashCharacters();
loops++;
Did you
if(loops < 12) { notice?
setTimeout(gameLoop, 3000);
} Variable We leave a space at the end
else { of our alert text, so the message
alert("You scored " + gameScore); displays correctly with the
} gameScore value.
}
Guest OK
Hurray! The
diamond will surely
be safe now!
179
function createCharacters() {
var board = document.getElementById("board");
var classToSet = peopleVisible ? "character visible" : "character hidden";
for(var index = 0; index < 6; index ++) {
CSS classes
board.children[index].className = classToSet;
added
board.children[index].innerHTML = "Guest";
board.children[index].onclick = function() {
gameScore += –2;
}
}
var randomNumber = Math.floor(Math.random() * 6) + 1;
board.children[randomNumber–1].innerHTML = "Thief";
board.children[randomNumber–1].onclick = function() {
gameScore++;
}
}
This function now does everything. Every time the game loop runs, it picks up the correct CSS class, creates
the characters and then sets the onclick for each character. We no longer need the flashCharacters
function, so we can delete it. Also delete the function call from your gameLoop function so it looks like this:
180
181
182
board.children[randomNumber–1].innerHTML = "Thief";
board.children[index].innerHTML = "";
board.children[randomNumber–1].innerHTML = "";
Security Ga
Save your HTML file. Now
your game will just be made
up of pictures. Play
183
Start screen
Security Ga
Play
Play
184
We’re using a simplified if statement, like we did earlier in the mission. We’ve changed our setTimeout call
so that if peopleVisible is true, our gameLoop function will be called in 1 second. If peopleVisible is false,
our gameLoop function will be called in 3 seconds. So now our characters will only flash on-screen for 1
second, but when they’re invisible they will be hidden for 3 seconds.
Save your code and start playing your finished game. Can you score 6 points?
o
ssi n DO IT YOURSELF TASK
Mi
Check that you have correctly coded all the things below in your securitygame.html file
and that it’s saved in your Coding folder. Don’t forget you can change the speed of your
game, making it faster and even harder for the user.
Turn over to see
A game board A play button the full code block
5 guests A score alert for the game.
1 thief
185
186
187
Dear Coder,
T HE E XPLORER ’ S This entry is about the discovery of the stolen jewel. For the entry about the
ENCYCLOPEDIA diamond’s history, see here.
The Guide to Every Adventure
Home page The Discovery of the Monk Diamond was the discovery of the stolen Monk
Contents Diamond, made by Professor Bairstone and Dr Day in Siberia. Professor Bairstone had
Featured discoveries
long believed that the Bond Brothers were responsible for the theft and that they had
Famous explorers
Historical expeditions hidden the jewel far away from the House of Volkov in Moscow, where it was stolen.
Dear Coder,
I just wanted to write you a short note to say
thank you so much
for all you have done to bring the Monk Diam
ond back to the
House of Volkov. I was heartbroken when it was
stolen and in my
darker moments I thought I would have to sell
the business. The
House of Volkov has been run by my family for
generations and
it would have been devastating. But thanks to
you, Professor
Bairstone, Dr Day and Ernest, the Monk Diam
ond has been
returned. I am so delighted to be hosting the
exhibition and have
the jewel on display in the shop.
As you know, a reward was offered for its safe
return or the
capture of the Bond Brothers. Professor Bairstone
and Dr Day
have taken their share and are going to use it
to fund another
expedition together. I want you to know that
I also have a token of
gratitude to give to you. It will be waiting for
you when you come
to Moscow to see the Monk Diamond for yourself.
With very warm and kind regards,
Viktor Volkov
Professor Bairstone is an explorer, known for discovering ancient artefacts around the world. He is always
accompanied on his expeditions by Ernest, his dog. Before finding the Monk Diamond, his most notable
discovery was the Hoy Hoard of Viking treasure, which he unearthed on the Orkney Islands in Scotland.
Dr Day is a scientist who studies fossils. She is currently researching a new species of feathered dinosaur. She
has been on several different expeditions in the hope of discovering fossils to prove that this species had feathers.
The news that the Monk Diamond had been found in Siberia and returned to the House of Volkov made
headlines all over the world. The team were interviewed for lots of different TV stations and have featured in
many newspapers and magazines. Professor Bairstone has been invited to give lectures about the discovery
and his biography will be published next year. Dr Day has been made a senior fellow at her university.
The special exhibition at the House of Volkov has been very popular. Mr Volkov told reporters he was “delighted
by the return of the diamond and the success of the exhibition”. Queues of up to two hours were reported
outside the House of Volkov and sales of jewellery have more than doubled.
Wireframes Menu
bar A big
Wireframes are a useful way of planning the image
content and layout of a website before you Wireframe
192
As we work through this mission, we’ll look at a wireframe for each page of our website. You can then
code each web page in your text-editing program using the HTML, CSS and JavaScript skills you’ve learnt
in all the other missions.
Using images
When you add images to your pages, you can change the size of them in lots of different ways. The best
way to do it is to add a style attribute to your <img/> tag and set the width CSS property to a value in
pixels (px) or a percentage (%), like this: Style attribute Pixels
193
A good way to create an interesting layout is to use <div> tags to divide your page into different sections.
If you want to use an image as the background for a <div> and create a banner, you should use the
background and background-size CSS properties like you did in Mission 5. There are different ways to
scale your images using CSS properties.
194
You can make images and text line up in two simple ways, which we looked at in Mission 1. You can use
the text-align CSS property on the <div> that has the text and image inside it. Or you can use the float
CSS property in a style attribute inside your <img/> tag, like this: Float property
CSS
Home
Header
banner
Title
The Monk Diamond
An extraordinary exhibition
Menu
bar The Diamond / Discovery / Exhibition / The House of Volkov
The Monk Diamond is one of the rarest and most valuable diamonds in Europe. It has a
fascinating history. It was owned by Russian nobility, stolen by a famous criminal gang
and then found hidden in remote mountains in one of the most sensational discoveries of
the century. Find out more about the Monk Diamond in this website or come and see it for
yourself at the House of Volkov in Moscow.
Text
Button
Visit the House of Volkov
197
Menu bar
Create a <div> in the <body> of your page. Menu
Add a style attribute to your <div> tag and bar Big
set the width, padding and background-color image
CSS properties. Add four hyperlinks, using The Diamond
each other.
Big image
In your <style> block, create a CSS
class with the width property set to 100%, The Monk Diamond is famous for its distinctive green colour. A Russian nobleman bought
the diamond for his wife in 1889, but it was stolen during the Russian Revolution. For
the height set to 200px and the padding the next 30 years, the Monk Diamond’s whereabouts were unknown. In 1947 it was
discovered during a police raid on a gang of petty criminals in Moscow. It was returned
to the nobleman’s family. The nobleman’s son decided the Monk Diamond was unlucky
set to 0px. Use the background and and sold it to the House of Volkov, Moscow’s oldest jewellery house. The House of Volkov
paid an undisclosed sum for the jewel, but it was rumoured to be the most expensive
diamond sale ever.
background-size CSS properties to add an
image. Apply this CSS class to a second
<div> in the <body>.
198
Menu bar
This should be the same as the menu bar Menu
on the diamond page. Remember to update bar Big
the links. image
Discovery
Big image
In your <style> block, create a CSS class
with the width property set to 100%, the Home / The Diamond / Exhibition / The House of Volkov
height set to 200px and the padding set to
0px. Use the background and background-
size CSS properties to add an image.
Apply this CSS class to a second <div>
in the <body>. Professor Bairstone and Dr Day, along with Ernest the dog, were on an
expedition in Siberia when they discovered the Monk Diamond. It had
been hidden in a remote mountain cave. The Bond Brothers attempted to
Text column sabotage the expedition and reclaim the diamond but were unsuccessful.
The team returned to Moscow with the diamond and a special exhibition is
being held at the House of Volkov to celebrate their discovery.
199
Menu bar
This should be the same as the menu bar Menu
on the diamond and discovery pages. Just bar Big
remember to update the links. image
Exhibition
Big image
This should also be the same as the diamond
and discovery pages. Home / The Diamond / Discovery / The House of Volkov
Text
Create a <div> for each section of
information.
You can indent pieces of text using the style The Special Exhibition
attribute and setting the CSS margin property The House of Volkov
Opening times
to 10px. Monday to Friday
9.30–6.00
Last admission 5.30
Footer Saturdays and Sundays
Make this the same as the home page. 11.00–4.00
Last admission 3.30
Admission: Free
Please note cameras are not allowed inside the House of Volkov.
Text
Footer
200
Menu bar
This should be the same as the menu bar Menu
on the diamond, discovery and exhibition bar Big
pages. Just remember to update the links. image
The House of
Big image
This should also be the same as the diamond,
discovery and exhibition pages. Home / The Diamond / Discovery / Exhibition
Text column
Create a <div>, using the style attribute
to set the width to 80% and the padding
to 50px. Add your text using the <p> and The House of Volkov
<br/> tags to divide the text into sections. The House of Volkov is the oldest jewellery
house in Moscow.
Please come and visit us.
Map column We are near to St Basil’s Cathedral.
Address:
Create another <div> and use the style The House of Volkov
attribute to set the width CSS property to St Basil’s Cathedral
Moscow
20%. Float this <div> to the right of the
<div> with your text in.
Contact Professor Bairstone: profbairstone@intrepidexplorer.com
Add an <iframe> and set the width, height
and border attributes. Then add a source
attribute with a URL that links to the Google Text
Map
Maps Embed API. Use the search API column
column
function and embed a map showing St Basil’s Footer
Cathedral in Moscow.
Footer
Make this the same as the home page.
201
<a href="index.html">Home</a>
<a href="diamond.html">The Diamond</a>
<a href="discovery.html">Discovery</a>
<a href="exhibition.html">Exhibition</a>
<a href="volkov.html">The House of Volkov</a>
S
notes to do it, drawing a wireframe that shows what of an object. The prototype is
their website will look like before they start to code. used to see what needs to be
This is sometimes called paper prototyping. It’s a changed and improved in later
really quick way to experiment with your layouts versions and the finished object.
before you spend time coding them up.
If you want to make wireframes like the
ones we’ve used here, there are plenty of tools
available. You can use Microsoft Visio on a PC,
Gliffy and Balsamiq mock-ups in a web browser, or That's the
OmniGraffle if you’re on a Mac. All these programs final mission
come with pre-made graphics that you can use to accomplished!
quickly sketch out your pages on a computer.
202
CODE
S
At the start of the book we learnt about web website so web browsers can
servers. They can be hardware or software and access it we say the server
they store websites so your web browser can HOSTS the website. When files
access them. For people to be able to see your are hosted by a server, they’ll have
website, you need to host it on a web server on a URL (web address) just like all the
the Internet. Setting up your own web server is other websites on the Internet.
complicated, so luckily there are lots of online
companies that will let you use their servers to
host your files. If you want to find a free web server to host your
website, you will be able to find lots to choose
from on the Internet. Just search for “free web
Did you
know? hosting”. Sometimes home Internet connections
come with web space that you can use. Once you
If you want to host your files, you should have a web host, you’ll have to copy your files
ask an adult for help to look for web to their server. Carefully read the instructions and
space on a server. Just like with a Google terms and conditions that your web host gives you.
account, you have to be a certain age to
sign up.
And we're
famous!
203
We hope Get Coding! has shown you how fun The W3Schools HTML site, which can be found
and interesting coding can be. You’ve learnt a truly at www.w3schools.com/html, will guide you
impressive number of new Code Skills and built through plenty of examples so you can expand your
some exciting projects of your own. And there’s still knowledge and make even more exciting websites.
much, much more to learn. If you enjoyed coding If you enjoyed coding in JavaScript, why not
in HTML and CSS, there are plenty of other HTML sharpen up your skills by working through some of
tags and CSS attributes that you can learn from lots the exercises available on sites like Codecademy at
of excellent websites on the Internet. www.codecademy.com/learn/javascript?
Or you could start learning new programming
languages for coding programs that run outside
your browser. Why not try learning C#, Java
or Ruby? Or try your hand at coding your own web
g servers? Take a look at www.code.org/learn for
u r c odin more ideas.
Yo re
futu ere! And finally, don’t forget to join the Young
ts h Rewired State community. We will help you to
star keep developing your coding skills and be a
technology star of the future!
The Get Coding! missions have been a great
success. It’s now up to you where you go next.
204
Keep on
coding!
We’ve loved
meeting you !
205
206
password 86–93
percentages 42
207
The right of Young Rewired State and Duncan Beedie to be identified as author and illustrator respectively of this work has been asserted
by them in accordance with the Copyright, Designs and Patents Act 1988
All rights reserved. No part of this book may be reproduced, transmitted or stored in an information retrieval system in any form or by any means,
graphic, electronic or mechanical, including photocopying, taping and recording, without prior written permission from the publisher.
www.walker.co.uk
www.getcodingkids.com