Cook P. Fundamentals of HTML, SVG, CSS and JavaScript For Data Visual. 2022
Cook P. Fundamentals of HTML, SVG, CSS and JavaScript For Data Visual. 2022
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean
Publishing process. Lean Publishing is the act of publishing an in-progress ebook using
lightweight tools and many iterations to get reader feedback, pivot until you have the
right book and build traction once you do.
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Setting up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 CodePen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Stay in touch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Translators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3. HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1 Headings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.3 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.4 <div> element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.5 <svg> element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.6 Wrapping up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4. SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.1 Adding SVG to a web page . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.2 SVG elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.3 SVG Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5. CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.1 The Structure of CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.2 CSS Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.3 CSS Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.4 More CSS selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.5 CSS for HTML layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
6.1 JavaScript variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
CONTENTS
1.1 Setting up
In order to get started quickly I recommend using CodePen1 to look at and experiment
with code examples (see next section). At the end of this book, in the ‘Tools and Set-up’
chapter I show you how to set up tools so that you can write code locally (where the files
are stored on your computer instead of on CodePen). This takes a bit of time to set up
but I recommend this approach if you become more serious about web development.
1.2 CodePen
CodePen2 is a web site that lets you experiment with HTML, SVG, CSS and JavaScript
without having to set up any tools.
NOTES 2
At key points in the book there’ll be a link to a CodePen ‘pen’ that contains a code example.
If you visit the link you’ll be able to view and experiment with the code. I encourage you
to play around with the CodePen examples - there’s very little you can break and learning
through experimentation is very effective.
You can freely edit the CodePen examples from this book and your changes don’t affect
the original example. If you want to keep your changes, click Fork (at the bottom of the
page) and create a CodePen account (or log in). Save your work by clicking the Save
button at the top of the page.
1.4 Translators
If you’re interested in translating Fundamentals of HTML, SVG, CSS and JavaScript for
Data Visualisation to another language contact me at info@createwithdata.com and I’ll
be happy to discuss further.
Notes
1 https://codepen.io/
2 https://codepen.io/
3 https://mailchi.mp/085e79e8fd7c/create-with-data-newsletter
2. Web languages: HTML, SVG, CSS
& JavaScript
Most websites and web applications (including data visualisations) are built from 4
languages: HTML, SVG, CSS and JavaScript.
HTML stands for Hyper Text Markup Language and describes the content of a webpage.
SVG stands for Scalable Vector Graphics and describes shapes such as circles, lines and
rectangles. It’s often used when visualising data (to describe bars, lines, circles, axes,
legends etc.).
CSS stands for Cascading Style Sheets and describes the style (such as font weight, colour
or size) and position of HTML and SVG elements.
JavaScript is a programming language that can manipulate HTML and SVG, do general
computation (such as data manipulation) and handle interaction.
We’ll look at each of these in the upcoming chapters.
3. HTML
HTML is a language that defines the content of a webpage. It defines a webpage using
elements to define headings, paragraphs, images, links etc. For example a paragraph
element looks like:
The paragraph element consists of an opening tag <p>, some content and a closing tag
</p>. Tags usually come in pairs. An opening tag looks like <p> and a closing tag looks
like </p>.
When a web browser loads an HTML document it draws each element according to the
type of element (paragraph, heading, image etc.). For example, the paragraph element
above looks like the following when rendered in a web browser:
There’s a large number of HTML elements but you can achieve a lot with just a few of
them. This chapter looks at five common elements: headings, lists, images, div elements
and svg elements. (These five elements are usually sufficient when visualising data.)
3.1 Headings
Heading elements are used for titles. There are six levels ranging from large (<h1>) to
small (<h6>).
HTML 5
<h1>Main heading</h1>
<h2>Sub heading</h2>
<h3>Level 3 heading</h3>
<h4>Level 4 heading</h4>
<h5>Level 5 heading</h5>
<h6>Level 6 heading</h6>
The web browser determines how each of these elements is styled. For example
the <h1> is the largest and all the headings are rendered with bold text. You
can set the style yourself using CSS (see the CSS chapter).
3.2 Lists
The list element <ul> is used to represent lists of items. Each item is represented by a list
item element <li> and nested within the <ul> element:
<ul>
<li>List item one</li>
<li>List item two</li>
</ul>
Notice that we’ve indented the <li> elements. This is optional but is the usual way to
indicate nested elements. When displayed in a browser the list looks like:
By default list items are bulleted and displayed as a vertical list. However
you can change how a list looks using CSS. Often navigation menus are
represented using a list and CSS used to hide the bullet points and position
the items as desired.
3.3 Images
Images can be added to an HTML document using the <img> element. <img> elements
require an attribute named src that specifies the URL of the image.
Attributes can be added to the opening tag of any HTML element and
they specify additional information about the element. They take the form
name="value" where the value is always in quotes.
Image elements don’t have a closing tag. Here’s an image element that displays an image
located at https://picsum.photos/id/127/300/200.jpg:
<img src="https://picsum.photos/id/127/300/200.jpg">
Typically your image files will live alongside your source code. For example, you might
have an image file my-image.jpg within a directory named images. In this case you’d
write:
<img src="images/my-image.jpg">
By default images are displayed at their original size. You can set the display width
(or height) of an image using the width (or height) attribute. Let’s set the width of the
previous image to 200 pixels:
HTML 7
<div>
<h1>Main title</h1>
<h2>Secondary title</h2>
</div>
<div>
<h3>Article title</h3>
<div>
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
</div>
Notice how the elements have been indented. This is optional and doesn’t affect how the
elements appear in the browser but it’s useful when reading and working with the code.
The above example looks like the following when rendered in a web browser:
See if you can relate each HTML element to each line of output.
By default the <div> elements don’t affect how the HTML is rendered. In other
words, the above HTML will look the same with or without the <div> elements.
However you can add CSS to style the <div> elements. For example you could
add margins to each <div> to add more space between the headings.
HTML 8
Inside the <svg> element are two attributes: width and height. These are similar to the
width and height attributes in <img> elements.
It’s quite important to specify the SVG element’s size (using width and height attributes)
because its default size is quite small and shapes are cropped to the SVG’s boundary.
SVG will be covered in greater depth in the SVG chapter.
3.6 Wrapping up
There are many other HTML elements but when visualising data the ones covered in this
section are the most common.
You can see a comprehensive list of HTML elements at https://developer.mozilla.org/en-
US/docs/Web/HTML/Element4 .
Most of the examples in this book are presented using CodePen which makes it
very easy to get started. However it doesn’t reveal the whole story. Web pages
are typically made up of individual HTML, CSS and JavaScript documents.
HTML documents typically contain extra information that CodePen doesn’t
show. We’ll look at this in more detail in the ‘Tools and set-up’ chapter.
3.7 Exercises
Here’s some HTML that includes most of the elements covered in this chapter:
NOTES 9
<div>
<h1>Main header</h1>
<h2>Sub header</h2>
</div>
<div>
<h4>Article title</h4>
<div>
<p>First paragraph</p>
<img src="https://picsum.photos/id/127/300/200.jpg">
<p>Second paragraph</p>
<ul>
<li>List item one</li>
<li>List item two</li>
</ul>
<p>Third paragraph</p>
</div>
</div>
Notes
4 https://developer.mozilla.org/en-US/docs/Web/HTML/Element
5 https://codepen.io/createwithdata/pen/ExQGeeY
4. SVG
SVG (Scalable Vector Graphics) is a language for describing shapes. It has a similar
structure to HTML but it describes shapes rather than text. The most common SVG
elements when visualising data are:
Element Description
<line> Line
<rect> Rectangle
<circle> Circle
<text> Text
Each element requires a number of attributes to define its position and size. We saw in
the HTML chapter that an attribute looks like name="value" and is inserted inside an
opening tag. For example:
In the above snippet the <svg> element has two attributes width and height and the
<circle> element has an attribute r with value 100. We’ll see later that the r attribute
specifies the circle radius.
4.2.1 Line
<line> elements represent straight lines. They have 4 attributes:
For example:
defines a line whose start coordinate is (50,50) and end coordinate is (200,50). Each
attribute is measured in pixels. The above example looks like the following:
In SVG the coordinate (0,0) is at the top-left of the SVG element. The x
coordinate goes from left to right and the y coordinate goes from top to bottom.
Although it seems unnecessary SVG elements do require a closing tag!
By default, SVG lines are white, so without additional CSS rules they won’t
show up! You’ll lean about styling using CSS in the next chapter and the
Codepen example also contains a CSS rule for setting the line colour.
SVG 12
4.2.2 Rectangle
For example:
defines a rectangle whose top-left corner is at (50,50) and has a width of 200 pixels and
height of 50 pixels. This example looks like:
A <rect> element
4.2.3 Circle
For example:
Make sure you use cx and cy (and not x and y) when defining a circle’s center.
4.2.4 Text
<text> elements have 2 attributes x and y which define the bottom-left corner of the text.
Unlike most SVG elements, <text> elements have content between the opening and
closing tags:
4.2.5 Group
<g> elements are used to group SVG elements and are particularly useful when an object
is made up of a few elements. They’re a bit like HTML’s <div> elements. For example a
circle with text label could be represented as:
SVG 14
In practice you should position the circle at (0,0) and transform the group as
a whole (see the next section on transformations).
4.2.6 Path
<path> elements have a single attribute d which contains a list of drawing commands:
Therefore:
A <path> element
4.2.7 Exercises
Here’s some SVG that includes most of the elements covered in this chapter:
SVG shapes
SVG is a cornerstone of web-based data visualisation. Most data visualisation you see on
the web (particularly if it’s interactive) is SVG based. Typically they’ll be made up of the
elements you’ve covered in this section. Next time you see a data visualisation on the
web see if you can identify some of the shapes that might be in use.
<circle transform="translate(100,100)"></circle>
SVG transforms include translate, rotate, scale, skewX and skewY. In this section we’ll
cover translate and rotate as these are common in data visualisation.
4.3.1 Translate
<circle r="50"></circle>
The default position of a circle is (0,0) which corresponds to the origin at the top left of
the SVG container (represented by the grey box below). This looks like:
You can apply a translate transform to the circle using translate(x,y) where x and y are
the amounts to move by in the x and y directions:
SVG 17
The above transform moves the circle by 200 in the x direction and 75 in the y direction.
This results in a circle centered at (200,75):
You can apply transforms to any type of SVG element including g elements. Suppose you
have a <g> element containing a circle and a text label:
<g>
<circle r="50"></circle>
<text y="6">Label</text>
</g>
<g transform="translate(100,75)">
<circle r="50"></circle>
<text y="6">Label</text>
</g>
This has the effect of moving the circle and text element by the same amount:
SVG 18
This is a very common pattern when working with SVG. You’re often grouping
items together and I recommend transforming the group as a whole (rather
than transforming or positioning each individual element).
Note that in this example I’ve added some CSS to horizontally center the label.
See the CSS chapter to learn more about CSS.
4.3.2 Rotate
Suppose you have a rectangle:
You can apply a rotate transform using rotate(a) which rotates an element by a degrees
in the clockwise direction about the origin (0,0):
The rectangle has rotated 20 degrees about the origin (0,0). (The origin is the top left
corner of the SVG container.)
You can specify a new center of rotation by adding coordinates after the angle. The
following rotates the rectangle about its center (150,60):
It’s important to understand that the transforms specify transformations of the coordi-
nate system. For example, in the above code snippet, the coordinate system is rotated by
45 degrees then translated by (100,0).
Let’s have a closer look how transforms combine. Here’s a rectangle without a transform:
The coordinate system has rotated by 45 degrees and the rectangle is drawn in the
transformed coordinate system.
Now let’s add a translation of 100 pixels in the x direction:
The coordinate system is 1) rotated about the origin by 45 degrees then 2) transformed
by 100 pixels in the direction of the rotated x-axis. (The coordinate system with just the
rotate transform is shown faintly.)
4.4 Exercises
Here’s the labelled circle SVG:
NOTES 21
Try the following (see if you can guess the effect before changing the code):
1. Change the translate transform and observe the effect on the labelled circle group.
2. Add a rotate transform after the translate and see the effect on the group.
Notes
6 https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths
7 https://codepen.io/createwithdata/pen/poJqELb
8 https://codepen.io/createwithdata/pen/MWwZjPp
5. CSS
CSS (Cascading Style Sheets) is a language for styling and positioning HTML and SVG
elements. Styling means changing the appearance (such as size, colour and font) of
HTML and SVG elements.
In the next section we look at the structure of CSS. We then look at CSS measurement
units followed by common CSS properties.
h1 {
color: green;
font-size: 20px;
}
Each rule comprises a selector and a list of declarations. In the above example the
selector is h1 and the declarations are color: green; and font-size: 20px;.
The selector defines which HTML or SVG elements are to be styled. The declaration
defines how the elements are to be styled. Each declaration consists of a property and a
value. In the declaration color: green; the property is color and the value is green.
The rule in the above example mean that on all h1 elements the colour is set to green and
the font size to 20 pixels (in height). As an example, suppose you have an <h1> element:
<h1>The title</h1>
h1 {
color: green;
font-size: 20px;
}
you get:
px Pixels 12px
Typically the web page’s default font size is 16px so 1.5rem means 24px.
These units are usually sufficient when building data visualisations.
Colour name A colour name. The full list of possible colours is red, green, steelblue
here9 .
CSS 24
RGB rgb followed by red, green and blue values in rgb(255, 100, 255)
brackets, expressed as numbers 0 to 255.
Hex code A # symbol followed by red, green & blue values in #FF595E, #FD3
hexadecimal (00 to FF). If all three values have
duplicate digits e.g. #FFDD33 you can shorten it to
#FD3.
In my experience the above colour units are sufficient when building data visualisations.
If you wish to dive deeper take a look at MDN’s guide to HTML colour10 .
border Border (around the content solid (solid line), 1px More13
of the element) dashed red (red dashed line)
For simple cases, set font-family to serif or sans-serif. You can specify font
names such as Helvetica but some fonts might not be available in everyone’s
browser. You can also use web font services such as Google Fonts22 but this
requires additional setting up which is beyond the scope of this book.
5.3.2 Exercises
Here’s some HTML:
p {
font-size: 1rem;
color: #335C67;
background-color: #FFF3B0;
border: 1px solid #aaa;
padding: 2rem;
margin: 1rem;
width: 12rem;
}
1. Edit some of the property values (for example you could change some of the
colours).
2. Add a rule for changing the opacity of <p> elements.
3. Increase/decrease the margin and/or padding to see how they relate.
4. Increase the border width.
5. Reduce the element width.
6. Add another <p> element to the HTML and observe how it looks in the result pane.
fill The shape’s internal colour red, #FF595E, rgb(255, 100, More24
255), none
stroke The colour of the shape’s red, #FF595E, rgb(255, 100, More25
outline 255), none
circle {
fill: #9E2A2B;
}
text {
font-family: sans-serif;
fill: white;
text-anchor: middle;
}
The first rule sets the colour of the circle and the second rule styles the text element. The
font family, colour and horizontal alignment of the text element are set.
Navigate to https://codepen.io/createwithdata/pen/YzeWeyY32 to view this example in
CodePen.
5.3.4 Exercise
Try the following:
p {
font-size: 10px;
}
p {
font-size: 1.5rem;
}
results in p elements having a font size of 1.5rem. (The first rule is overriden by the
second.)
5.3.6 Example
Let’s look at a more advanced example. Suppose you’ve the following HTML:
<h1>Main title</h1>
<h2>Subtitle</h2>
<div>
<p>Some description text</p>
</div>
<div>
<svg width="600" height="300">
<circle cx="150" cy="150" r="100"></circle>
<rect x="300" y="50" width="100" height="200"></rect>
</svg>
</div>
body {
font-family: serif;
}
h2 {
color: #aaa;
font-family: sans-serif;
}
p {
color: #333;
}
CSS 29
circle {
fill: orange;
}
rect {
fill: none;
stroke: #aaa;
stroke-width: 1px;
}
p {
color: #333;
}
sets the colour of all <p> elements. However what if your web page contains lots of <p>
elements and you only want to style some of them?
You can do this by making CSS selectors more specific using these approaches:
These approaches cover most cases where you need to target specific elements. Let’s look
at them one by one.
5.4.1.1 id
The id attribute lets you label a single element so that you can reference it elsewhere
(typically with CSS or JavaScript). For example, you might have a main menu that needs
some CSS applied to it.
Let’s create a simple menu and add an id attribute with value main-menu:
<div id="main-menu">
<div>Home</div>
<div>About</div>
<div>Blog</div>
<div>Contact</div>
</div>
You can add ids to more than one element but each id value must be unique. In other
words: two elements should not have the same id.
In CSS, to select an element with an id use a # followed by the id value:
CSS 31
#main-menu {
margin: 1rem;
}
5.4.1.2 class
The class attribute is used to label multiple HTML and SVG elements. For example:
<div id="main-menu">
<div class="item">Home</div>
<div class="item">About</div>
<div class="item selected">Blog</div>
<div class="item">Contact</div>
</div>
Each menu item is given a class attribute with value item. Class attributes can have more
than one value (separated by a space). For example the third item’s class attribute has
two values: item and selected. This indicates that this particular div element is an item
in a list and has been selected.
In CSS, an element with a given class value may be selected adding a dot followed by
the class name to the element type:
div.item {
border: 1px solid #aaa;
padding: 1rem;
}
div.selected {
background-color: #ccc;
}
This means:
• add padding and a border to each div element with class value item
• set the background colour of div elements with class value selected
You can also select all elements, regardless of type, with a given class value by omitting
the element name. For example .item selects all elements with class value item.
5.4.2 Exercises
Here’s a simple menu built using HTML and CSS. The HTML is:
CSS 32
<div id="main-menu">
<div class="item">Home</div>
<div class="item">About</div>
<div class="item selected">Blog</div>
<div class="item">Contact</div>
</div>
#main-menu {
margin: 1rem;
width: 15rem;
}
div.item {
border: 1px solid #aaa;
padding: 1rem;
}
div.selected {
background-color: #ccc;
}
A menu built with HTML and CSS with the second item selected.
<div id="main-menu">
<div>Home</div>
<div>Posts</div>
</div>
<div id="content">
<div>Some content</div>
</div>
You can style the div elements within the #main-menu element using the selector #main-
menu div. For example:
#main-menu div {
padding: 1rem;
}
This means select all div elements that are descendants of the #main-menu element. The
div elements outside of the menu are not selected.
Descendant selectors are a very common device and examples related to data visualisa-
tion include:
.bar-chart .bar {
fill: blue;
}
.chart .legend .label {
font-family: sans-serif;
font-size: 0.75rem;
}
The first selector .bar-chart .bar selects elements with class bar that are nested within
elements with class .bar-chart. (In other words, bar chart bars.)
The second selector .chart .legend .label selects elements with class label that are
nested within elements with class legend that are nested within elements with class chart.
(In other words, chart legend labels.)
Descendant selectors are handy because they let you select elements based on the nested
structure of your elements. For example you can recreate the previous menu example
using descendant selectors. Here’s the HTML:
CSS 34
<div id="main-menu">
<div>Home</div>
<div>About</div>
<div class="selected">Blog</div>
<div>Contact</div>
</div>
#main-menu {
margin: 1rem;
width: 15rem;
}
#main-menu div {
border: 1px solid #aaa;
padding: 1rem;
}
#main-menu div.selected {
background-color: #ccc;
}
Notice that we’re able to remove the class="item" attributes from each item. Instead
of using div.item to style menu items, we use #main-menu div. This has simplified the
HTML, making it easier to read and maintain.
Navigate to https://codepen.io/createwithdata/pen/BaYzYZb35 to view this example in
CodePen
p:hover {
background-color: yellow;
}
The above changes the background colour of <p> elements to yellow when hovered over.
Pseudo classes commonly used when building data visualisations include:
CSS 35
Here’s the menu example using pseudo classes to style the first item (which now
represents the menu title) and the hovered item. The HTML is:
<div id="main-menu">
<div>Main</div>
<div>About</div>
<div class="selected">Blog</div>
<div>Contact</div>
</div>
#main-menu {
margin: 1rem;
width: 15rem;
}
#main-menu div {
border: 1px solid #aaa;
padding: 1rem;
}
#main-menu div:first-child {
font-weight: bold;
}
#main-menu div.selected {
background-color: #aaa;
}
#main-menu div:hover {
background-color: #ccc;
}
CSS 36
The first div within #main-menu has been made bold by using the :first-child pseudo
class. When any item is hovered over the background colour changes because of the
:hover pseudo-class. (In reality you wouldn’t implement a menu quite like this so this
example just serves as a teaching tool.)
Navigate to https://codepen.io/createwithdata/pen/MWQeQvy36 to view this example in
CodePen
<h1>Main heading</h1>
<h2>Sub heading</h2>
<h6>Small heading</h6>
The following CSS sets the font weight of all heading elements to lighter:
Dashboard layout
It takes some skill to position HTML elements using CSS. On one level it can be
straightforward, but it can also be tricky. One of the challenges is that you’re rarely
working with a fixed size page. (It would be much easier if you were!) People might be
reading your page on a mobile, tablet, laptop or large desktop monitor. You usually need
to take into account all these different screen widths.
Having said this, there’s a couple of recent CSS developments that make arranging your
elements much easier: Flexbox and Grid. We’ll give an overview of Flexbox in this book.
CSS Grid is a newer development and isn’t covered. It could take a whole book to cover
HTML layout in detail and hopefully this section is able to give you a flavour of what’s
possible.
From a layout perspective HTML elements can be divided into two categories: block
elements and inline elements.
Block elements are positioned below each other and inline elements are positioned side
by side. For example if you have several <div> elements:
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
Block elements
Inline elements
Of the elements covered in this book, heading (<h1> - <h6>), list <ul> and <div> elements
are block elements (by default) and <img> and <svg> elements are inline elements (by
default). You can also set whether an element is block or inline using the display CSS
property. To set an element to block display use:
display: block;
display: inline;
Another value for display is inline-block which positions elements side by side and
allows their width and height to be set using width and height properties. (I very rarely
use display: inline; but occasionally use display: inline-block; when positioning
<div> elements side by side.)
CSS 39
The direction in which block and inline elements run depends on the writing
language. This book assumes the writing language is English.
5.5.2 Flexbox
The CSS Flexbox model lets you specify how items are arranged within their parent
element. For example, let’s start with this HTML:
<div id="container">
<div class="item">ONE</div>
<div class="item">TWO</div>
<div class="item">THREE</div>
<div class="item">FOUR</div>
</div>
.item {
padding: 1rem;
margin: 0.25rem;
border: 1px solid #aaa;
}
Flexbox lets you specify properties on the container and its child elements (or ‘items’) to
specify how the items are arranged.
To make an element a flex container set the display property of the element to flex:
CSS 40
#container {
display: flex;
}
You can now set properties on the container and/or the items to determine how the items
should be arranged. These are the most common properties and values for the container:
The main axis is determined by flex-direction and runs left to right if flex-direction is
row and runs top to bottom if flex-direction is column. The cross axis is perpendicular
to the main axis. See https://css-tricks.com/snippets/css/a-guide-to-flexbox38 for more
detail.
As an example, if we set justify-content to space-between:
#container {
display: flex;
justify-content: space-between;
}
we get:
You can also nest flex containers inside one another. For example you can build a
rudimentary header bar using this approach. Here’s the HTML:
CSS 42
<div id="header">
<div id="title">My Website</div>
<div id="menu">
<div>Home</div>
<div>About</div>
<div>Contact</div>
</div>
</div>
body {
margin: 0;
font-family: sans-serif;
}
#header {
height: 4rem;
background-color: #222;
color: white;
padding: 0 1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
#menu {
display: flex;
}
#menu div {
padding-left: 1rem;
}
The outermost <div> element represents the header. It has two children: a title and a menu.
The header element acts as a flex container (display is set to flex on #header). The title
and menu are arranged at opposing ends of the header by setting justify-content to
space-between. The items are vertically centered within the container by setting align-
items to center.
In order to arrange the menu items in a row, the menu element (#menu) is also made a
flex container (its display property is set to flex). Thus the menu is both a flex container
and a flex item.
The finished header looks like:
NOTES 43
Hopefully this gives you a flavour of what Flexbox can achieve. If you’d like to learn
more about Flexbox one of the best tutorials is https://css-tricks.com/snippets/css/a-guide-
to-flexbox39 . I’ve also built a Flexbox explorer (https://app.peterrcook.com/flexplorer/40 )
which lets you quickly explore each property interactively.
Notes
9 https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
10 https://developer.mozilla.org/en-US/docs/Web/HTML/Applying_color
11 https://developer.mozilla.org/en-US/docs/Web/CSS/color
12 https://developer.mozilla.org/en-US/docs/Web/CSS/background-color
13 https://developer.mozilla.org/en-US/docs/Web/CSS/border
14 https://developer.mozilla.org/en-US/docs/Web/CSS/padding
15 https://developer.mozilla.org/en-US/docs/Web/CSS/margin
16 https://developer.mozilla.org/docs/Web/CSS/opacity
17 https://developer.mozilla.org/en-US/docs/Web/CSS/font-size
18 https://developer.mozilla.org/en-US/docs/Web/CSS/font-family
19 https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
20 https://developer.mozilla.org/en-US/docs/Web/CSS/width
21 https://developer.mozilla.org/en-US/docs/Web/CSS/height
22 https://fonts.google.com/
23 https://codepen.io/createwithdata/pen/OJQXzKo
NOTES 44
24 https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
25 https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
26 https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
27 https://developer.mozilla.org/docs/Web/CSS/opacity
28 https://developer.mozilla.org/en-US/docs/Web/CSS/font-size
29 https://developer.mozilla.org/en-US/docs/Web/CSS/font-family
30 https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
31 https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor
32 https://codepen.io/createwithdata/pen/YzeWeyY
33 https://codepen.io/createwithdata/pen/LYVvBEg
34 https://codepen.io/createwithdata/pen/VwQjQpX
35 https://codepen.io/createwithdata/pen/BaYzYZb
36 https://codepen.io/createwithdata/pen/MWQeQvy
37 https://codepen.io/createwithdata/pen/jOPoMBK
38 https://css-tricks.com/snippets/css/a-guide-to-flexbox
39 https://css-tricks.com/snippets/css/a-guide-to-flexbox
40 https://app.peterrcook.com/flexplorer/
6. JavaScript
JavaScript is the programming language of the web. It’s built into the majority of web
browsers and can:
10 + 5; // 15
The value indicates the value that the code returns. (If you type 10 + 5 into jsconsole and
press return it’ll show the result 15 on the next line.)
let myMessage;
let is the modern way of declaring a variable. The older way is to use var.
The differences are subtle and are beyond the scope of this book. You can read
more here46 .
JavaScript statements usually end with a semicolon ;. This is optional but we’ll
use them in this book.
You can assign a value (such as a number or string) to a variable. Here’s how to assign a
string (a piece of text enclosed between quotation marks) to the variable myMessage:
let a = 10;
let b = 20;
(The above code uses a shorthand where the variable is declared and assigned in a single
statement.)
Any expression can be assigned to a variable.
let c = a + b;
c; // 30
6.1.0.1 Exercises
let a = 10;
let b = 20;
let c = a + b;
Now type c followed by the return key. The c variable will be evaluated and its value 30
is ouput.
The above are sufficient to build data visualisations. We’ll look at strings, numbers and
booleans in this section. There are separate chapters for arrays and objects.
6.2.1 Strings
Strings represent text. The text is enclosed by single quotes (') or double quotes ("):
If your text contains a single quote you use double quotes to enclose it (and vice versa):
a.length; // 16
You can get the nth character in the string using square brackets:
a[0]; // "T"
a[2]; // "i"
A string can be split wherever a string s occurs using split(s). For example let’s split
the string by a single space character:
(The square brackets represent an array which we’ll cover in a subsequent section.)
You can compute the upper case version of a string using toUpperCase():
Note that this doesn’t change (or mutate) the string. It just returns a new string and a’s
value is still "This is a string". To make variable a upper case you can assign the output
of a.toUpperCase() to a:
a = a.toUpperCase();
a; // "THIS IS A STRING"
You can convert a string containing a number into a number using parseFloat. For
example:
JavaScript 49
parseFloat('123.456'); // 123.456
parseFloat('5432'); // 5432
parseFloat('abc'); // NaN (not a number)
parseFloat('1234abc'); // 1234
parseFloat('0'); // 0
parseFloat(''); // NaN
Note that passing an empty string into parseFloat returns NaN which means ‘not a
number’.
It’s quite common to see the + operator used to convert strings into numbers.
For example +'123' evaluates to 123. You need to use with caution because
converting an empty string (e.g. +'') evaluates to 0. Sometimes when working
with data, missing data is represented by an empty string and if this is
converted using + it’ll evaluate as 0 which isn’t always desirable.
6.2.1.3 Exercises
a = "This is a string";
a.length;
a[2];
a.split(' ');
a.toUpperCase();
16
"i"
["This", "is", "a", "string"]
"THIS IS A STRING"
6.2.2 Numbers
JavaScript has a number type for representing numbers. Integers (whole numbers) and
decimals may be represented:
JavaScript 50
let a = 123;
let b = 123.456;
(10 + 20) * 2; // 60
10 + (20 * 2); // 50
The first expression evaluates as 60 and the second one 50. (An expression is a piece of
code that evaluates to a single value.)
The following examples use a variable n with value 123.456:
let n = 123.456;
Math.round(n); // 123
Math.floor(n); // 123
Math.ceil(n); // 124
n.toString(); // "123.456"
Math.sqrt(100); // 10
6.2.2.1 Exercises
let n = 123.456;
Math.round(n);
n.toString();
Math.sqrt(100);
123
"123.456"
10
6.2.3 Booleans
You’ll see later on (in the operators section) that booleans are returned by operators such
as === (is equal to) and > (is greater than).
You can access the ith item in an array by writing [i] after the array:
JavaScript 52
Arrays are indexed from 0. So the first element in an array is referenced by [0]. For nested
arrays such as:
Join each element of an array with a.join(' and ') "10 and 20 and 30"
a given string
Join two arrays a.concat(b) [10, 20, 30, 40, 50, 60]
Add an element to the end of an b.push(70) b is now [40, 50, 60, 70]
array
Remove (and return) the last a.pop() Evaluates to 30. a is now [10, 20]
element of an array
The remaining operations just evaluate to a value. They don’t have any effect on the
array.
6.3.3 Exercises
let carrot = {
foodGroup: "vegetable",
color: "orange"
}
Each name-value pair is known as a property. Each property has a name (e.g. foodGroup,
color, id, height, data) and a value. The value can be any type (including array or object).
You can access properties using a dot followed by the property name:
carrot.foodGroup; // "vegetable"
An object’s property may also be accessed using the property name (expressed as a string)
enclosed in square brackets:
carrot["foodGroup"]; // "vegetable"
The advantage of the square bracket notation is that a variable can be used as the property
name:
let data = {
Monday: 20,
Tuesday: 30,
Wednesday: 10,
Thursday: 50,
Friday: 70
};
data[day]; // 30
let data = {
Monday: [10, 30, 20],
Tuesday: [50, 20, 30],
Wednesday: [40, 10, 20],
Thursday: [30, 10, 20],
Friday: [60, 30, 40]
};
You can also have arrays of objects. This is a very common structure in data visualisation:
let data = [
{
name: "Spain",
capital: "Madrid",
population: 46.66
},
{
name: "China",
capital: "Beijing",
population: 1386
}
];
data[0].name; // "Spain"
data[1].capital; // "Beijing"
let vegetable = {
name: "carrot",
color: "orange"
};
vegetable.name = "broccoli";
vegetable.color = "green";
vegetable.name; // "broccoli"
You can use the above notation even if the property doesn’t exist:
JavaScript 56
vegetable.family = "Brassica";
6.4.1 Exercises
Open jsconsole52 and create the following object:
let carrot = {
foodGroup: "vegetable",
color: "orange"
}
Use shift + return instead of just return to insert new lines within a single statement.
Or click here53 for a pre-populated console.
Type the following:
carrot.color;
Check that this returns the string "orange". Now change the colour to purple by typing:
carrot.color = "purple";
carrot.color;
This should output "purple". You can also view the object by typing:
carrot
Now add a new property named price with value 15 to the object and check that it’s
been added.
let a = 1;
let b = 2;
>, >=, <, <= Greater than, greater or 5 < 6, 5 < 5, 5 <= 5, "a" true, false, true, false,
equal to, less than and > "b", "abc" < "def", a true, false
less than or equal. > b
Note that the equality operator is three equal signs ===. This operator checks that two
expressions are exactly equal. There’s a similar operator == which is less strict. In general
I recommend using ===.
let a = 10;
let b = 20;
let result = a > b ? "a is bigger than b" : "a is not bigger than b";
result; // outputs "a is not bigger than b"
In this example the expression a > b is evaluated. If true the first expression after the
question mark is evaluated. If false the expression after the colon : is evaluated.
let a = 10;
a++;
a; // 11
a = a + 1;
6.5.3 Exercises
Open jsconsole54 and define two variables:
let a = 10;
let b = 20;
1. Add a and b.
2. Multiply a and b.
3. Check whether a is greater than b.
4. Check whether a is equal to b.
5. Check whether a is equal to 10.
6.5.3.1 Answers
a + b; // 30
a * b; // 200
a > b; // false
a === b; // false
a === 10; // true
6.6.1 if
let answer;
if (a > b) {
answer = "a is greater than b";
}
let answer;
if (a > b) {
answer = "a is greater than b";
} else {
answer = "a is not greater than b";
}
let food = {
name: "banana",
type: "fruit"
};
let answer;
6.6.2 switch
The switch statement executes different blocks of code depending on the value of an
expression:
let food = {
name: "banana",
type: "fruit"
};
let answer;
switch(food.type) {
case "fruit":
answer = "It's a fruit!";
break;
case "vegetable":
answer = "It's a vegetable!";
break;
default:
answer = "Unknown food";
break;
}
The switch statement is followed by an expression wrapped in brackets (in the example
the expression is food.type). There are a number of case statements followed by possible
values of the expression (such as "fruit" and "vegetable"). If there’s a match, the code
following the case statement is executed. The code following a case statement is executed
up until the break statement.
JavaScript 61
It’s important to include the break statements otherwise the following case
statements will also execute. In general, add a break statement at the end of
each case block.
var food = {
name: "banana",
type: "fruit"
};
switch(food.type) {
case "fruit":
case "vegetable":
alert("It's a fruit or a vegetable!");
break;
default:
alert("Unknown food");
break;
}
In general use if if the test expression returns true or false and switch if the
test expression returns multiple values.
let a = 10;
let b = 20;
let doubleA = a * 2;
let doubleB = b * 2;
If the operation is more complicated than doubling a number this approach becomes
harder to manage. An alternative approach is to define a function that takes a number
and returns the double of the number:
JavaScript 62
function double(x) {
return 2 * x;
}
let a = 10;
let b = 20;
let doubleA = double(a);
let doubleB = double(b);
function sayHello() {
console.log('Hello'); // console.log lets you print a value to the console
}
A function is (usually) given a name. In the above example the function name is sayHello.
You place a pair of brackets after the function name. The function’s body (the code
that gets executed when the function is called) is placed between curly braces. To call
a function you write the name of the function followed by brackets:
sayHello();
console.log is a function built into JavaScript that lets you output a value.
Where the value is displayed depends on where you’re running JavaScript. If
you’re using jsconsole it’ll appear below your code.
function getName() {
return "Paris";
}
If you call getName it runs the function’s code and returns the expression after the return
keyword:
getName(); // "Paris"
let message;
You can define a list of values that are passed into your function. For example let’s define
a function that joins a first name and last name (with a space between):
return joinedName;
}
This function has a list of parameters (firstName and lastName) inside its round brackets.
These behave as variables within the function body. When the function is called a list of
arguments is placed inside the round brackets:
JavaScript 64
When the joinNames function executes each argument is assigned to the function
parameters. In the above example, when the function executes firstName is Ana and
lastName is Matronic.
6.7.4 Exercise
Create a function called add10 that adds 10 to a number. Test your function by calling it
with an argument 50:
add10(50);
• for loops
• forEach
• map
These three iteration types cover most cases when visualising data.
In the above code the body of the for loop (console.log(i)) is executed while i is less
than 3. The output will be three numbers: 0, 1 and 2.
for loops are useful when you know how many times you want to iterate. For example
if you wanted to create an array containing 5 items you could do something like:
let numItems = 5;
let data = [];
6.8.2 forEach
Given an array, forEach iterates over each element of the array. You provide forEach with
a function that gets called for each array element. Each time the function is called the
array element is passed into the function:
data.forEach(function(d) {
console.log(d);
});
In this example the function is called once for each array element. The first time it’s called,
the first element of the array 10 is passed into the function. The second time it’s called,
the second element of the array 20 is passed in, and so on. In this instance the function
gets called a total of five times.
Notice that the function doesn’t have a name. This is an example of an anonymous
function. These are functions that are defined ‘on the fly’ and typically aren’t called
from anywhere else in the code. They’re covered in the JavaScript functions (advanced)
chapter.
You can rewrite the above using a named function:
JavaScript 66
function output(message) {
console.log(message);
}
data.forEach(output);
This is more verbose, but does allow the function to be reused elsewhere.
When iterating over an array you can also use a for loop:
However I recommend using forEach if possible because it’s more expressive. (‘Expres-
sive’ means that the intent of the code is clearer to another developer.)
6.8.3 map
The map statement takes an array and returns a new array with the same length. Each
element of the new array is computed from the corresponding element in the original
array. A function determines how the new values are computed.
Here’s an example where map is used to iterate over data and outputs a new array where
each element is doubled:
For each element in data the function is called. For the first element 10 is passed into the
function. The function returns 10 * 2 and this’ll get assigned to the first element of the
new array. The second time it’s called 50 is passed in and 50 * 2 is returned and added
to the new array. And so on.
map is very common when working with data. For example given the data:
JavaScript 67
let data = [
{
name: "Anna",
value: "20.1"
},
{
name: "Brian",
value: "15.3"
}
];
we might want to convert the name property to upper case and the value property from
a string into a number.
First write a function that takes an object (with properties name and value) and returns a
new object with the two properties converted:
function convert(d) {
let newObject = {
name: d.name.toUpperCase(),
value: parseFloat(d.value)
};
return newObject;
}
[
{
name: "ANNA",
value: 20.1
},
{
name: "BRIAN",
value: 15.3
}
]
return newObject;
});
It’s a matter of design whether you use an anonymous function with map. The
advantage of anonymous functions are they keep the map and function in the
same place so can be easier to read. The advantage of using a named function
with map is you can reuse that function elsewhere in your code.
6.8.4 Exercises
Open jsconsole55 and create an array of numbers:
1. Use forEach to iterate over the array, outputing the square of each number. (Use
console.log to output a number.)
2. Use map to create an array containing the square of each element of a.
Remember to use shift + return to create new lines within a single statement in
jsconsole.
6.8.4.1 Answers
a.forEach(function(d) {
console.log(d * d);
});
function addTen(x) {
return x + 10;
}
This allows them to be called anywhere in your program. However when using forEach
or map (see the iteration chapter) it’s often convenient to use an anonymous function.
This is a function without a name and is defined as the first argument of forEach or map.
So instead of writing:
function output(message) {
console.log(message);
}
data.forEach(output);
data.forEach(function(message) {
console.log(message);
});
This results in more concise code and is a very common pattern in JavaScript. (D3 uses
this pattern very often.) I highly recommend understanding this pattern properly. Study
the two code examples above and try to understand the difference and similarity between
the two.
JavaScript 70
A pure function is a function that doesn’t have side effects. A side effect is when
something outside of the function changes. For example:
function doSomething() {
outside = 20;
}
Calling doSomething results in the variable outside changing. This is considered a side
effect. An example of a pure function (where there are no side effects) is:
function doSomething() {
return 20;
}
outside = doSomething();
The function just returns a value and does not affect anything outside of the function.
The advantage of pure functions is that they have more predictable behaviour. They have
input values (via the argument list) and a single output. You know that if you call a pure
function it’s not going to cause anything to change outside of that function.
JavaScript functions behave like objects. This means you can do anything to a function
that you can do to an object. For example you can assign a function to a variable:
getANumber();
function getANumber() {
return 10;
}
getANumber();
let myFunctions = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
myFunctions.add(10, 20); // 30
myFunctions.subtract(20, 10); // 10
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
When getValue is first called, the add function is passed in and assigned to the operation
parameter. Thus when operation is called (inside getValue) add is executed.
In the second call to getValue, the multiply function is passed in meaning that opera-
tion‘s value is multiply. Thus when operation is called, multiply is executed.
Notes
41 https://d3js.org/
42 https://leafletjs.com/
43 https://www.chartjs.org/
44 https://jsconsole.com/
45 https://developers.google.com/web/tools/chrome-devtools/console#javascript
46 https://javascript.info/var
47 https://jsconsole.com/
48 https://jsconsole.com/
49 https://jsconsole.com/
50 https://stackoverflow.com/questions/48201502/strange-javascript-sorting-bug
51 https://jsconsole.com/
52 https://jsconsole.com/
53 https://jsconsole.com/?let%20carrot%20%3D%20%7B%0A%20%20foodGroup%3A%20%22vegetable%22%
2C%0A%20%20color%3A%20%22orange%22%0A%7D
54 https://jsconsole.com/
55 https://jsconsole.com/
56 https://codepen.io/createwithdata/pen/abvJmPY
7. Tools and Set-up
This book has used CodePen for code examples. CodePen’s a reasonable tool for building
small applications but larger applications are typically developed locally. This means
using tools and files on your computer (rather than on the web). This chapter outlines a
typical set up for developing web applications locally. This is similar to the set-up most
web developers use.
The first section gives an overview of the necessary tools and the second section walks
you through setting up these tools.
• a code editor
• a web browser
• a web server (not so important if you’re not loading data)
You could also add a terminal emulator to this list. A terminal emulator allows you
to interact with your operating system via text commands. For example Terminal (on
MacOS) and the Command shell (on Windows). You can work through all the material
in this book without a terminal emulator so I won’t cover them in this book. If you’d like
to learn more I suggest a web search for ‘command line tutorial’.
A code editor is a desktop application that allows you to edit HTML, CSS and JavaScript
files. You can use simple applications such as Notepad (on Windows) and TextEdit (on
Mac). It’s important that these editors work in plain text mode so that they don’t insert
extra characters. However I recommend using a dedicated code editor such as Brackets57
or Visual Studio Code58 . Both of these are free and multi-platform. Advantages of using
a dedicated code editor include:
• you can treat your application as a project making it easier to open and navigate
Tools and Set-up 74
Adobe dropped support for Brackets but at the time of writing it’s been
resurrected by the open source community. It does seem to be in a state of
flux so keep checking its status if you’re interested.
A modern web browser such as Chrome, Firefox, Safari or Edge is recommended for web
development. Create With Data books assume that Chrome is being used. The majority
of material will apply regardless of your browser choice but there may be differences if
the debugging tools are used, as these differ from browser to browser.
A web server typically returns (or ‘serves’) HTML, CSS and JavaScript files in response
to requests from a web browser. For example if you type createwithdata.com into a web
browser the browser connects with a web server and requests files that make up that
website. The web server responds by sending the requested files back to the browser.
When you create a web site on your own computer you don’t necessarily need your
own web server running. (You can open an HTML file directly in most web browsers.)
However if you need to make requests from within your web application (as is usually
the case with web based data visualisations) you will need your own local web server.
(This is due to security restrictions in web browsers.) If you’re an experienced developer
and are comfortable setting up a local web server, feel free to skip ahead.
The options for running a local web server (starting at the easiest) include:
Another option which I’ve not personally explored is Servez59 which is a simple GUI
based web server.
Tools and Set-up 75
Brackets61 has a built in web server so this is by far the easiest option. This video62 gives
a good demonstration. If you’re new to code editors I recommend using Brackets.
Visual Studio Code has a web server plug-in called Live Server63 .
To install Live Server:
• select ‘View’ and then ‘Command Palette…’ from the menu bar
• search for ‘live server’ (by Ritwick Dey) in the extensions search box and click
Install
Tools and Set-up 76
Your web browser should then open your web application. If it doesn’t, open a web
browser and go to localhost:5500. (If a different port number to 5500 is shown in the
‘Server is Started’ message, use that number instead.) More detailed instructions are
here64 .
If you’re a Python, Ruby or PHP developer you can use the language’s built in webserver.
There are some useful instructions here65 . MacOS includes Python and Ruby so you can
use one of these if you’re a Mac user. If you’re a JavaScript developer using Node you
can use http-server66 .
We’ll use VS Code and its Live Server extension. If you’re comfortable using a different
editor and web server then please feel free to do so.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My webpage</title>
</head>
<body>
<h1>Hello!</h1>
</body>
</html>
Usually the only code you’ll need to change is the title (between the <title> tags and the
content (between the <body>) tags.
The <!DOCTYPE>, lang="en" and charset="utf-8" are standard bits of code that
tell the browser how to interpret your HTML file. Although your webpage may
appear to work without these it’s best to leave them in. (See here68 for more
information about character encoding if you’re interested.)
Select Save from the File menu, navigate to your project directory, name your file
index.html and click Save. (It’s important to name your file index.html.) Once your
file is saved you should see index.html appear in the sidebar.
If you haven’t already, select Open Folder… from the File menu and select your my_-
website directory. You should see your new directory appear in the sidebar. Now click
on the Go Live button that appears in the bottom bar.
Make sure your browser is pointing at ‘localhost:5500’ (use whichever port number is
displayed in the bottom bar).
Your page should now be visible in the web browser (it should say ‘Hello!’). Try editing
your HTML file, saving it, then refreshing your browser. The changes you’ve made should
be visible.
In this section you’ll add a CSS file and a JavaScript file to your web page. There are
usually two steps to adding a file to a web page:
• create the file and save it (with extension .css for CSS files or .js for JavaScript
files)
• include the file in your index.html file
Select New from the File menu and add the following CSS code to the new file:
Tools and Set-up 80
style.css
h1 {
color: orange;
}
Select Save from the File menu and when the dialog appears create a new directory called
css within your project directory. Go into the css directory then save your new file as
style.css. You’re aiming for the following directory structure:
my_website
css
style.css
index.html
You now need link to your CSS file in index.html. Start editing your HTML file by clicking
index.html in the left sidebar. Add the line with the <link> tags (highlighted below):
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My webpage</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Hello there!</h1>
</body>
</html>
Save index.html and check your browser (you might need to refresh the page). The title
should now be orange.
Select New from the File menu and add the following JavaScript code to the new file:
Tools and Set-up 81
main.js
alert("Hello!");
Select Save from the File menu and when the dialog appears create a new directory
within your project directory called src. Go into the src directory then save your new
file as main.js. You’re aiming for the following directory structure:
my_website
css
style.css
src
main.js
index.html
If your files aren’t in the above structure you can drag them into their correct
location in the left sidebar of VS Code. You can also right click files and
directories for more options.
You now need to add a link to your JavaScript file in index.html. Start editing your HTML
file by clicking index.html in the left sidebar. Add the line containing the <script> tag
(highlighted below):
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My webpage</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Hello there!</h1>
<script src="src/main.js"></script>
</body>
</html>
Save index.html and check your browser (you might need to refresh the page). An alert
should appear saying ‘Hello!’.
NOTES 82
7.2.7 Summary
This section has shown how to set up a web development environment consisting of:
• a code editor
• a web browser
• a local web server
You saw how to create a simple web site consisting of an HTML file, a CSS file
and a JavaScript file. This is the basis for most web applications and web-based data
visualisations.
Notes
57 http://brackets.io/
58 https://code.visualstudio.com/
59 https://greggman.github.io/servez/
60 https://github.com/http-party/http-serverhttps://github.com/http-party/http-server
61 http://brackets.io/
62 https://youtu.be/KJXdvaY9lTA?t=122
63 https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
64 https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
65 https://gist.github.com/willurd/5720255
66 https://www.npmjs.com/package/http-server
67 https://code.visualstudio.com/
68 https://www.w3.org/International/questions/qa-what-is-encoding