Intro To Web Design

Intro To Web Design

In the previous step I wrote about Sir Tim Berners-Lee inventing the web by linking documents together. This developed into Hypertext Markup Language (HTML), which is now the standard language for creating webpages. Now you are going to look at what makes a webpage and how webpages appear on your devices, by working with a Raspberry Pi Fan Club page.

HTML HTML uses tags to define elements of a webpage; for example, the tags can make the text appear in different sizes.

Throughout this week you will use this Trinket to show how a Raspberry Pi Fan Club webpage uses HTML. Trinket shows the HTML (including all the tags) on the left and the resulting webpage on the right. It is important to recognise the relationship of each line of the HTML to what appears on the webpage. You can change the text slightly on the left and see it change on the right.

Sign up and log in to Trinket using the links at the top-right.

Correct the launch date of the Raspberry Pi 4 to 24 June 2019 in the Trinket for the Raspberry Pi Fan Club webpage.

In Trinket, click on “Remix” (at the top right of the screen) and save your Trinket, as you will be using your own version in the next steps.

You will notice some tags open and close by using a /, such as

and

; however, not all tags need to close, for example
and
do not.

The Raspberry Pi Fan Club webpage you looked at in this Trinket uses only a limited number of tags, which is similar to early webpages. As webpages increased in popularity and usage, developers wanted images and other media to appear. This meant that more tags were created to define these elements; you will learn more about some of them in the next steps and use them to improve the Raspberry Pi Fan Club webpage.

Browsers and HTML pages Today you may use one of these common web browsers: Microsoft Edge, Google Chrome, Mozilla Firefox, or Apple Safari. The function of the web browser is to process the HTML (and other code) to appear in the web browser’s window. This displays what we see as the webpage.

Browser icons for Safari, Firefox, Chrome and Explorer

HTML is not programming You may now be starting to think that HTML is a programming language, but it is not. HTML is a markup language that uses tags to identify elements of a webpage and tells a browser how to lay a webpage out on a screen.

By contrast, computer programming is a way of giving computers instructions about what they should do in order to complete a set task. A computer program will have the ability to take input data from a device such as a keyboard, process calculations, and make decisions based on certain conditions.

Unlike a programming language, HTML does not:

Use logic Use conditional statements such as If/Else Use mathematical expressions Take inputs Produce outputs Declare variables Write functions To view webpages, browsers use Hypertext Transfer Protocol (HTTP) as the rules to send and receive HTML. HTTP is called a “stateless protocol”, because each request is executed independently, without any knowledge of the requests that were executed before it. There is no requirement to store user data on the web server and every visitor to a website will be given the same information.

How do you make the Raspberry Pi Fan Club webpage interactive? HTML is not programming, but you can still program for the web using JavaScript. JavaScript allows the webpage to respond to actions from the user without the need to load a new webpage. You will learn more about JavaScript in week three HTML structure and tags 440 comments In this step you will learn about the basic structure of a webpage and look at more tags to use for your Raspberry Pi Fan Club page.

Compare the basic HTML structure below to your Raspberry Pi Fan Club webpage:

<!DOCTYPE html>

Page Title

This is a Heading

This is a paragraph.


Any information within the tags is hidden and used by browsers and web crawlers; this is known as metadata. Also notice that some tags are nested inside other tags; in the example below, is nested inside and is nested inside . The image below shows how elements can exist inside other elements: Diagram showing how nesting works. Each tag from the HTML above labels a rectangle, with some rectangles contained within others. The title rectangle is inside the head rectangle, which is itself within the html rectangle. The body rectangle is also inside the html rectangle, but below the head rectangle. It contains a p rectangle below a h1 rectangle. The p rectangle contains an em rectangle and a strong rectangle. The table below describes the tags that have been used in the basic HTML structure above: Tag Description <!DOCTYPE> This is a declaration to show the document type; it helps the web browser to display the webpage correctly This defines the title of the webpage, to be displayed on the tab of a web browser This shows the start and end of the HTML file This gives information about the file (metadata) This defines the main body; everything within the body tags appears on the webpage

This defines a heading;

to

tags are used for different-sized headings, with

the largest and

the smallest

This defines a paragraph Headings and lists Headings are used to start a new section, to help the reader understand the purpose of that part of the webpage You use

and

headings to introduce different sections, such as the “Raspberry Pi 4“ header that sits inside the “Raspberry Pi Fan Page” section of your Raspberry Pi Fan Club webpage. Think of

headings like the chapters of a book. Those individual sections might also use more specific headings (

tags, then

tags, and so on) to introduce subsections. You can also use a list on your Raspberry Pi Fan Club webpage, to break a paragraph into key points. This can make the points stand out for the reader. To create a list on your webpage, you have two options: an unordered list

You can see the resulting webpage in this Trinket. Activity

In the Trinket above, add some more CSS to the style.css page to style the #myHeader id.
Add some more CSS to style the .city class.

The box model 66 comments

The box model is used when discussing a webpage design because web browsers display HTML elements within a rectangular box. The CSS determines the size, position, and properties of each box.

When you have previously styled the background of an element, the background colour took up the whole width of the page, not just the area with text on it; the box extended beyond the content. You can control each box by changing the size of the width and height of the content and the size of the margin, border, and padding:

Diagram of box model showing concentric rectangles, starting from the outside going in they are headed; margin, border, padding & content. The margin and padding are see-through, while the border is opaque. The central square (content) contains a picture. Width and height

The height and width properties are used to set the height and width of an element. The width and height measurements do not include the padding, borders, or margins.

Each new box element will automatically fill the entire width of a webpage (that is, 100 percent) within a browser, unless you give it a specific width, which can be set in pixels or as a percentage. A percentage is often better practice, as it scales to any screen your webpage is displayed on.

The CSS and HTML below will style the h1 element with a solid border and a background colour of green. It will also stretch the element across 50 percent of the screen’s width:

h1 { width: 50%; border: 1px solid red; background-color: green; }

<!DOCTYPE html>

This element has a width of 50 percent.

Margins

You can also change the size of the margins of each element, which are the spaces between the border and other elements. The margins are created by pushing other elements away.

CSS has properties for specifying the margin for each side of an element:

Margin-top
Margin-right
Margin-bottom
Margin-left

Each of these can have values of: Value Description auto the browser calculates the margin length specifies a margin in pixel (px) or centimeters (cm) % specifies a margin in % of the width of the containing element inherit specifies that the margin should be the same as that for the element it is nested within

A quicker way of sizing each margin, rather than setting margin-top, margin-right, margin-bottom, and margin-left individually, is to use the margin property. The values are written in the order: top, right, bottom, left, like this:

p { margin: 25px 50px 75px 100px; }

Padding

The padding property is used to create space between the border and the element. This Trinket gives an example of padding. Try changing the size of the padding and margin and see how this affects the appearance of the element. The display property

You may have thought that setting the width properties of elements on your page low enough will cause them to be arranged next to each other. However, by default they won’t; if you try it, you will see that the elements and content shrink, but they are still arranged one after another vertically.

If you want your page to fit together nicely, you will have to use the display CSS property. The default value of this property is block, which will arrange your elements as if each were a full page-width block, regardless of any box properties you have applied to the element.

The display property should be applied to containers, which will contain other elements, and not applied directly to the elements themselves. The containers will apply the display behaviour to the elements contained within them.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

If you change the display property of a container to flex or inline-flex, the elements nested within it will fit side by side if their total width is less than 100 percent.

In the HTML above, a

element with display set to flex contains two other
elements with a width of 50%. The two inner
elements will sit next to each other on the page. Inspect element

On a desktop or laptop, most web browsers have a feature that allows you to see the HTML and CSS of an element.

Open the Raspberry Pi home page on a desktop or laptop.
Right-click on an element and select “Inspect Element” or “Inspect”. You can see that the HTML has appeared within the browser window. (In Safari, you may need to enable this first. Click on Safari > Preferences, then on the Advanced tab. Then, selectShow Develop menu in menu bar”.)3. Click on the HTML code (sometimes found in the Elements tab) and change the text within the HTML; you should see it changing on the webpage.
Click on the Styles or Style editor tab.5. Click on a heading.
Change the CSS in the Styles or Style editor tab.

You can change the content of the webpage because you have downloaded it from a web server; when you refresh the page, your browser will download the original webpage from the web server.

Unscrupulous people can change the content of a webpage, take a screenshot of it, and use it to create fake news stories or alter social media posts. Using the box model 152 comments In this step you are going to use the box model to change the layout of your website, by changing the padding, borders, and margins, and by using the float property.

You will need to think about how your elements will look on your webpage. It is useful to consider the alignment of each element and in what order you want visitors to read the page. This is known as the visual hierarchy. Some cultures read from left to right and others read from right to left, so be aware of what you want your visitors to see first and last.

White space White space is the area on a webpage that is left unmarked or blank; it is the space between the elements. White space holds your webpage together and helps to shape the overall flow of the page; it is an active part of the layout and a fundamental building block of good design.

The white space between each element acts as a visual cue, showing relationships between the content of your webpage. Elements can be grouped together by reducing the white space. If you increase the white space, it will show a divide between the elements.

A cluttered webpage can overwhelm your visitors, confusing them with too much information and losing the page’s core message. By removing elements, you draw visitors’ eyes to the most important areas of the page. The more white space surrounds an object, the more the eye is drawn to it.

Image of a website using less white space to draw attention to the 'sign up now' button

White space doesn’t have to be white, though. You can use any colour in your white space. You could even use a pattern or a background image, but be careful that the image colours don’t hide any of the text that’s on top of it.

Float property The float property defines that an element should be taken out of its normal place on a webpage and placed along the left or right side of its containing box. All the other elements will then wrap around the element with the float property.

To control the position of the element, the float property can have the values: left, right, or inherit (which gives it the same value as the element it is nested in).

The CSS below will float every element to the right:

img { float: right; } The effect that this CSS would have on a linked HTML file containing the following HTML would be to make the image float to the right of the text, when the file is viewed in a web browser.

raspberry pi 1In this example, the image will float to the right of the paragraph, and this text will wrap around the image.

Open this Trinket and click on the “Float: Left”, “None”, and “Float: Right” buttons to see how the Raspberry Pi logo floats to the left and right of the text. Responsive design using CSS 103 comments It is important that your website can be viewed on various devices and screens. Responsive web design (RWD) adapts the content of a webpage so that all the information can be seen. Web developers first design websites to use with mobile phones; this allows them to focus on the key points and prioritise features of the websites that are necessary because of the smaller screen size and bandwidth. This approach is called “mobile-first design”. As the developers move onto designing a website for tablets and larger screens, they can take advantage of being able to put more content on the screen.

A website layout on a computer screen, with a title at the top, a sidebar at the left, and other content displayed as a grid.

Context RWD was developed in early 2010 in response to the increasing use of mobile digital devices. Before this, web designers made multiple versions of the same website so that it could be viewed on different devices. One of the major issues of this approach was that these different versions of the website existed independently of each other, making the site difficult to maintain.

Today, websites must be created to be viewed on all devices. RWD websites have one URL and one set of code, so developers do not need to design multiple websites. It does not matter if the visitor uses a tablet, a smartphone, or a laptop, they will see the same site. The website will automatically reorient and organise the elements to fit the device’s screen.

Viewport The viewport is the area of a webpage that is visible to a user. Before the use of tablets and smartphones, websites were designed for a desktop screen size, and fixed-size webpages were too big to view on the screen of a mobile device. To fix this problem, browsers were developed to scale down the webpage to fit on the screen, and the tag was used to dictate the viewport.

The tag is also used to specify metadata such as the page description, keywords, or author of the HTML document. The name attribute identifies the type of metadata, with the value for this metadata given as the content attribute. This metadata is not displayed on the webpage. The tag must be nested within the tag in the HTML.

The description meta tag is used by internet search engines as the description of the website in their search results.

A viewport meta tag gives the browser instructions on how to display the HTML on the screen. You should include the viewport element below in the of your climate change website. This will be used by the browser to scale the width of your webpage to fit the width of a screen, which will vary depending on the device being used.

Load your climate change website on a tablet or mobile phone. View the website with the device in portrait and landscape orientations. Go back to your Trinket. In the of your climate change webpages, add the viewport element from above. Load your climate change website on a tablet or mobile phone again. Can you see the difference that the meta tag has made? Add your comments below. If you cannot access a mobile device, the images below demonstrate the difference between using and not using the viewport meta tag:

A website on a tablet, the layout has changed to fit the screen, so the grid of content is less wide and the sidebar has been reduced to icons.

A website on a phone, the layout has changed to fit the screen. The header is now much smaller, there are icons in a bar at the bottom of the screen, and there are fewer items displayed in the grid.

Percentages In previous steps, you used percentages for the height and width of elements. You can use CSS to style the width of an image to be 100 percent; this will scale the image to fit across the full width of a webpage. However, this could lead to an image being stretched beyond its original size, possibly leading to pixelation.

You can use the max-width property to avoid this. This will allow the image to scale down, but not to scale up larger than the size set, which is often the original size of the image (100%):

img { max-width: 100%; height: auto; } Add the max-width and height properties to the img styling on your CSS for your climate change website. Change the max-width to 75 percent to see the effect it has on your webpage. Change the max-width to 50 percent to see the effect it has.

Welcome to week three 29 comments Welcome to the final week of Introduction to Web Development.

In week one you built a couple of webpages using HTML, and in week two you used CSS to specify the layout and style of those webpages. You also used classes and ids to refer to elements of the webpage. While you used these classes and ids for styling last week, these will also come in useful this week as you learn to use JavaScript, a common programming language used on the web.

You need JavaScript because, although your climate change website should now look visually appealing, the quiz page does not serve its purpose of being an interactive quiz — it does not do anything. You need to monitor what the visitor enters as answers to your questions, and give them a final score. To create this interactivity, you need to use JavaScript.

In summary, to create any website you will need to have knowledge of:

HTML, to define the content of the webpage CSS, to create the style of the HTML of the webpage JavaScript, to program what the webpage does This week you’ll write JavaScript functions to run the quiz on your website. You’ll learn about the Document Object Model and how JavaScript can work with this to change the structure of your site. After writing JavaScript to check the answers your user has submitted, you’ll also investigate how you can use APIs to extend your site’s functionality. Finally, you’ll create your own site to demonstrate what you’ve learnt over the course, and review sites created by your peers.

Enjoy!

Introduction to JavaScript 24 comments

In the early days of the web, most pages were static; HTML provided the structure of a webpage and CSS styled each element of HTML. There was a need for websites to be more interactive, to extend the functionality of a website for its visitors beyond just presenting information. In order to do this, a dynamic programming language was needed, to provide conditional statements, handle events, declare variables, and create functions. JavaScript began to be used to interact with the HTML and CSS of a website.

JavaScript became the standard programming language of the web because it was open and standardised. JavaScript’s syntax was also similar to the English language, which made it easier for people who were already familiar with English to learn JavaScript.

In this step I will give you some background about JavaScript and look at some other programming languages to give you more context about why you are going to use it on your webpage. Netscape v Mosaic

When the need for more dynamic webpages was first being discussed by software companies, Netscape Communicator was becoming a popular browser. It had become a competitor to the Mosaic browser in a very competitive marketplace. Netscape created a vision of the web being more dynamic and interactive in the future, to try and increase uptake of their browser. In order to realise this vision, Netscape created JavaScript to interact with the static HTML code. JavaScript made such a considerable difference when using Netscape that other browsers had no choice but to use it, too. Differences between JavaScript and Python

You may have used Python on one of our other FutureLearn courses, or heard about it being used for different applications. Python has become a popular language and is now commonly used for creating web applications (programs that run in a web browser and have similar functionality to a desktop software application) such as online word processors and online photo editing applications. Similarly, JavaScript dominates website development and is used to create highly responsive interfaces that improves the user experience.

Here is a summary of some differences between Python and JavaScript: Python JavaScript You have to install Python on your computer before you can use it JavaScript is mostly run in a web browser; there is no separate installation required for most uses Uses : and indentation to denote the code belonging to functions or “if… then” statements Uses curly brackets to contain the code belonging to functions or “if… then” statements Comes with a wide range of modules Comes with very few modules

The “Hello world” comparison below demonstrates the difference between Python and JavaScript syntax: Hello world in Python

print("Hello world") Hello world

A screenshot showing the Mu Python IDE. The code above is shown, and the REPL shows "hello world" Hello world in JavaScript

#Syntax for popup alert box on the browser

A screenshot showing the above HTML and JavaScript in Trinket, and a pop-up alert box reading "hello world" Client-side and server-side

When visiting a website, you may be asked to interact with the webpage, for example by filling out a sign-up form or by filling up a shopping basket and paying for some goods. There are two ways that a website can process these requests: client-side (on the client, or the device that is accessing the webpage) or server-side (on the server, or the device where the webpages are stored). When using Python for creating web applications, the files are stored on the server, so Python is known as a server-side programming language. Examples of server-side processing are uploading a new profile image to a social media platform, or updating a blog post. Server-side processing can cause webpages to load slowly, because a lot of data is going to and from the web server.

Client-side processing is when the webpage gets the client to do the processing, rather than the client having to make further requests from the server. JavaScript is executed by the client web browser on the client’s device. Advantages of this include the fact that less bandwidth is being used; the server has fewer requests to process and the browser is quicker to interact with the webpage. Debugging JavaScript

Unlike Python, when using JavaScript nothing is actually shown on the webpage; if there are errors these can be difficult to debug. The JavaScript above will not be shown anywhere on your webpage. You used the developer tool to change elements of HTML, and you are going to use the same developer tool to help you debug. Most web browsers have a developer tool; if you are not using Google Chrome, you may have to search for how to open your developer tool.

In Google Chrome, type about:blank in the address bar (this will open a blank page to avoid distractions).
Press F12 to open the developer tools.
Click on the Console tab.
Type the following into the console:

var message = "Hello world"; console.log(message);

When you press enter after the final line, you should see “Hello world” appear on the console. You have set the variable message to this text, and then used console.log to print this out. I will explain the use of var in a later step.

Your first JavaScript function 96 comments

Now that you’ve learnt about what JavaScript is, you are going to create your first JavaScript code, which will make something happen on your climate change webpage when a visitor clicks on a button. To do this, you’re going to need to create a function and respond to an event. Functions

A function is a way of putting code together so it can be reused. Functions let you run the same code from different places in your program, without needing to copy and paste that code into different places.

The JavaScript below defines a function:

function finishFunction() { alert("Thank you for completing the quiz."); }

To define this function in JavaScript, first I had to write function followed by the name I want to give this function: finishFunction. I then wrote the code that controls what happens in the function, between the curly brackets {}. This function produces an alert message in your browser that states "Thank you for completing the quiz." Later in this step you will learn how to call this function in order for it to execute. External JavaScript functions

JavaScript functions can be stored in an external file rather than added directly to the HTML, which is useful when the same code is used on many webpages — you used CSS in a similar way last week. An external JavaScript file makes it easier to maintain and read the HTML and JavaScript.

You are going to create your own external JavaScript file and link it to your HTML page:

Open your climate change website in Trinket.
Press the + icon to add another file next to the HTML and CSS files. Name the file script.js. All the JavaScript you write will go into the script.js file.
Add the JavaScript below into your script.js file.

function finishFunction() { alert("Thank you for completing the quiz."); }

To call and execute a function in JavaScript, you enter its name followed by a pair of opening and closing parentheses () (if the function requires parameters, these should be included inside the parentheses).

finishFunction();

To link the HTML file to the script.js file, enter the following HTML between the and tags in your HTML file. (You linked to your CSS file in a similar way last week.)

Events

At the moment, you cannot see any changes to your climate change webpage because you have not called the function to execute it. One way of calling a function to execute is to use an event. Events occur when the user or browser manipulates the page, for example when the page loads, or when the user clicks a button. The HTML below creates a button on the webpage using the and tags. The tag has an onclick event set, to call the finishFunction function when you press the button.

Finish

Add a button to your quiz page that will thank the user for completing the quiz when they click it.

You may want to use different events as you complete the rest of the week. For example, you may want to use the onmouseover event to change the background colour of an element when the mouse is hovered over it. When the mouse hovers away from the element you could then use the onmouseout event to change the background of the element back to its original colour. Event Description onmouseover The mouse hovers over an HTML element onmouseout The mouse moves away from an element onkeydown A keyboard key is pressed onload The browser has finished loading the page Uses of JavaScript

You can use JavaScript with your climate change website to:

Change HTML content
Add values of attributes
Update CSS styles
Hide elements
Show elements

The Document Object Model (DOM) 81 comments

The Document Object Model (DOM) is the representation of your HTML; it defines its logical structure and the way the document is manipulated. JavaScript is used within an internet browser to connect to the DOM in order to change the HTML elements. You are going to use the DOM to add content, remove content, and change content. HTML structure and the DOM

When you view HTML in a browser, the browser creates an internal model of the webpage, organising each element into a treelike structure. This is known as the DOM tree.

My first webpage

Hello, world!

How are you?

The DOM structure below is a representation of the HTML above. The element branches from the element, which is itself branching from the . The

and the

elements each branch from the element.

Flowchart showing DOM structure; it starts with 'html' which splits into 'head' and 'body'. 'Head' is connected to 'title' which leads into 'my first webpage'. 'Body' has 'h1 'and 'p' connected to it. 'h1' leads into 'Hello, world!' 'p' leads into 'How are you?'

JavaScript can use this DOM to access elements from the HTML, to both read and modify them. JavaScript

As you saw last week, you can use the id attribute to assign a unique name to an element. You can then use the document.getElementById method (which is part of the DOM) in JavaScript to return that element. Once the JavaScript has used the DOM to access an element, the JavaScript can change it, including changing its contents.

The example below shows an element in the HTML with the id "heading":

The DOM

In the JavaScript below, I have used the document.getElementByID method to call the element with the id "heading". The variable headingElement is then used to refer to this element, and I will be able to change the content of this element later, using JavaScript.

var headingElement = document.getElementByID("heading");

When you view photographs online, you may have had to click on a “Next” button to view the next photograph in a gallery. The JavaScript linked to the HTML page of the button replaces the innerHTML of the element with a new source for the next photograph. In the example below, I am going to use the innerHTML property to return the HTML content of headingElement, as well as to modify this HTML content.

Create a blank HTML Trinket.
Create a blank script.js page.
Enter a heading for your page, using the <h1> tag. Give this heading the id "heading".
Add the link to the script.js page at the end of the <body> of the HTML page.

<!DOCTYPE html>

The DOM model

Add the JavaScript below to your script.js page.

This will change the headingElement to a new heading that the visitor to the website enters in a prompt when your browser loads the page:

var headingElement = document.getElementById("heading"); console.log(headingElement.innerHTML); var newheading = prompt("Please enter new heading:"); headingElement.innerHTML = newheading;

The explanation of the code above is below:

The JavaScript will be executed as the browser loads the webpage
The HTML element with the id "heading" is saved to the headingElement variable
console.log prints headingElement.innerHTML — the content of the headingElement
A prompt dialog box asks the user to enter a new heading, and the text the user has entered is saved to newheading
The innerHTML property of headingElement is set to 'newheading', changing the text of the heading to what the user has entered

In the Trinket you have used in this step, create a new .js file alongside your HTML Trinket and enter the JavaScript shown above.

When your webpage is loaded (which may be done automatically by the Trinket) and the JavaScript is run, you should see a prompt dialog box like this:

Screenshot of a dialog window with the question "Please enter new heading:" followed by a text input box. The text "This is Awesome" has been entered into the input box.

Enter a new title and it should replace the original heading, as shown below.

Screenshot of the HTML code in Trinket and the title of the website having been changed to 'This is Awesome' More DOM methods

You have used the document.getElementByID method in this step to access the heading element; there are other methods that you can use to access elements using the DOM method:

The document.getElementsByTagName() method returns the collection of elements in the HTML with a specified tag; document.getElementsByTagName("li") will return all the <li> elements
The document.getElementsByClassName() method returns the collection of elements in the HTML with a specified class; document.getElementsByClassName("links") will return all the elements with the class name "links"
The document.forms method will return all the <form> elements; this also can be used to return elements nested within the form element, for example: document.forms.form1 will return all the elements within the form with the name form1

By using the DOM methods to access your HTML document, you can return any element and manipulate the content of each element. Over the next few steps you will use the DOM model to access elements so that you can hide elements, change the colour of the text, and ensure your visitor enters answers for your quiz.

Using the DOM 131 comments

In this step you will learn some of the other things you can do with elements that you’ve accessed using the DOM. You’ll learn how to use an onclick event, and to show and hide elements, before using these concepts on your climate change webpage to engage your visitors. Having fun with the functions and the DOM

Throughout this step you will use the HTML and JavaScript from this Trinket.

First, I am going to make a heading that, when clicked, will change the colour to a random colour. To do this, I’ll create a change_heading function that will use the DOM to access the heading, and will then change its style. This needs to be called when the heading is clicked, so it will be called by the onclick event. To make the code more readable, I’m also going to create a separate rndm_colour function to randomly select a colour; this function will be used by the change_heading function. Random-colour function

This Trinket contains the rndm_colour function, which returns a random hexadecimal (hex) colour value (#RRGGBB). The hex colour value can be used to set the colour of an element, as an alternative to a colour name; it indicates the intensities of red, green, and blue (RGB), on a scale of 0 to 255, that are combined to give a new colour. You can read more about hex values at w3schools and on our Data Representation course. Using the random-colour function

The change_heading function below will style the heading. First it will call the function rndm_color (created above) to randomly select an RGB colour value and store it as the colour variable. Then it uses the getElementByID DOM method to return the element with the id "heading", and styles it using the colour variable.

function change_heading() { colour = rndm_colour(); document.getElementById("heading").style.color = colour; }

Add the rndm_colour function to your JavaScript.
Add the change_heading function to your JavaScript, and edit it to style an element of your climate change website.

Using onclick events

Events are actions, such as a button being pressed, that can be detected by JavaScript. These events can be set to execute a function when the event occurs.

The HTML below shows an

tag with the id ""heading". The element nested inside is not creating a hyperlink; it is instead being used to detect an onclick event. When the words “Using the DOM” in the heading are clicked or pressed, the change_heading() function will be called.

Using the DOM

The HTML and the JavaScript above will change the colour style of the element with the id "heading" when the viewer clicks on the heading “Using the DOM”. Test this in this Trinket.

Open the HTML for your climate change webpage. Add the onclick event in the HTML to call the change_heading function that you have created.
Add to the change-heading function to also change the content of an element to a different font type, by setting .style.fontFamily.
Ask any questions you have about the JavaScript in the comments section.

Show and hide elements

It is useful to be able to show and hide elements with your HTML. For example, an online shop could include an option for you to click on to reveal more details about an item, or a button to show more detailed images. It’s common to want the visitor to be able to hide these elements afterwards, to avoid cluttering the page with too much information.

The display property of the style attribute of an HTML element controls whether it is visible or not. If the value of this property is set to "none" then the element will not be visible. You can make the element visible by setting the value of the property to "block".

The show_hide function below starts by setting a condition for the if statement. In JavaScript, the condition for the if statement is given within parentheses (). If the condition is true, the code within the first set of {} will run; if the condition is false, the code within the {} after else will run.

function show_hide(){ if (document.getElementById("appear").style.display == 'none'){ document.getElementById("appear").style.display = 'block'; }else{ document.getElementById("appear").style.display = 'none';}}

The following HTML sets the onclick event of the button to call the show_hide function.

Peekaboo
Click me! Read through the HTML and JavaScript. Predict what it will do, then try the “Click me!” button in this Trinket. Add a show and hide function to your climate change webpage to reveal an extra fact about climate change. Validating quiz answers 144 comments The previous steps have given you the knowledge and confidence to use JavaScript on your own climate change webpage. By using different functions and the DOM model, you have tried to make your site more engaging for your visitors. In this step you are going to make sure that the visitor to your climate change website completes all the questions on your quiz page. Validation Validation is a process of checking the inputs to a form are sensible, by comparing the input to a set of rules (conditions). If you have ever completed an online form, you may have forgotten to complete a question, or typed your date of birth in the name field. Often this will result in an error message on-screen, asking you to complete the missing or incorrect question — this is the result of validation taking place. Validating text inputs On your quiz page, add a question at the start of your quiz that will ask for the visitor’s name. The HTML below is an example of a text input that you were shown in a previous step:

Text input

Answer: This Trinket uses the validateText function below as an example of how to validate a text box. The name variable is used to store the value from the fname element, which is nested within the myform element of the HTML document: function validateForm() { var name = document.forms.myForm.fname.value; if (name == "") { alert("Name must be filled out"); } } The validateText function uses an if statement to check if the variable name is equal to (==) a blank string (""). If it is, an alert will appear in the browser. This function also returns true or false, to indicate if the data is valid. This will enable other JavaScript code to call this function and behave differently depending on whether the validation succeeds or fails.

Text box validation

Name: Submit I have added a element in the code above. The onclick event occurs when you press the button; in this example it will execute the validateForm function. Validating number entry You may want to ask for feedback on your quiz, for example asking your user to rate the quiz from 1 to 10. You could then use validation to check if the answer given is within the specified range. The JavaScript below uses the getElementById method to return the element with a numb id. The JavaScript below also includes comments. // makes the line a comment; when the program is run, the comments are ignored. This means that you can use them to explain the code on the following lines, to make your code easier to understand. function validateNumber() { var x, text; // Get the value of the input field with id="numb" x = document.getElementById("numb").value; // If x is not a number or less than one or greater than 10. || means OR in JavaScript if (isNaN(x) || x < 1 || x > 10) { alert("Number entry invalid"); return false; } else { return true; } } The condition uses the isNaN function in the condition to identify if the x is not a number. If any other data type other than a number has been entered, isNaN(x) will return true. This is used along with checks on the range of numbers and the boolean operator “OR”, so that the condition will be true if the input is invalid. The HTML calls the function when the button is clicked: Submit Add validation to your quiz question that uses a number input. Radio buttons Validation for radio buttons involves checking that at least one button is selected before the quiz is submitted. The JavaScript below checks that a value is present for the group of buttons; if there is no value present, an alert will appear in the browser. function validateRadio() { var x = document.forms.myForm.elements.radio.value; if (x === "") { alert("One radio button must be selected"); return false; }else{ return true; } } === is used in the JavaScript above to ask if both x has an equal value to "" and x has the same type as "". The HTML used to call the function is in the code below:

Radio button validation

China
USA
UK
Submit Add validation to your quiz question that uses radio buttons. Add validation to any remaining questions on your climate change quiz page. Combining functions Now that you have added validation to all of your quiz questions, you need to use functions together in order to validate all your questions one after another when a button is pressed. The JavaScript below shows the validateQuestions() function, which calls each of validateText(), validateRadio(), and validateNumber(). If any of the validation functions return false, the validateQuestions function will return false as well, indicating the data is not valid. function validateQuestions() { if (validateText() && validateNumber() && validateRadio()){ return true; }else{ return false; } } Add a function to your climate change quiz page to execute all of the functions you have created to validate each of your questions. Add a button with an onclick event set to call this function. Remove any unwanted buttons that you have previously created. Share Share a link to your Trinket in the comments section. Remember that you can also use the comments section to ask for help with this step. Calculating the score 104 comments Now that you have made sure that the person visiting your website has to submit a complete set of answers, it is time to mark those answers. To do this, you are going to create a function for each question. The function will use a condition to check if the answer is correct and add 1 to a score variable if it is. Checking the answers and scoring Below is the checkAnswers function. This function will check an answer to the first question and add 1 to the score variable if the answer is correct. function checkAnswers(){ // grab all the elements from the quiz form, store them as quiz quiz = document.forms.Quiz.elements; var score = 0 if (validatequestions(quiz)){ // check the answers // question 1 answer1 = quiz.q1Answer.value; if (answer1 == "China"){ score = score + 1; showFeedback(score); } } } The JavaScript above initially sets the score variable to 0. The condition calls the validatequestions function, using the parameter quiz. If this function returns true then the answer1 variable is set to the value of the q1Answer element on the form. The next condition checks if the answer1 variable is equal to "China" (the correct answer in this case - you will need to change this for each question in your quiz); if the condition is true the score variable increases by 1. The code then calls a function showFeedback- this is a function that will show the score (More about this one later in this step) Add JavaScript to your quiz to check the answers. For each question, your code should add 1 to the score variable when the answer given is correct. If you have any problems, ask for help in the comments. Returning the score Below is some of the HTML that can be used with the JavaScript above:

Which country emitted the most carbon dioxide in 2017: China, Russia, or UK?

Submit Answers I have included Submit Answers: this will call the checkAnswers function when the button is pressed. Change your HTML to add a button to your quiz page that will run the checkAnswers function when it is clicked. So that the webpage will be able to show the user their score, add the showFeedback function below to your JavaScript: function showFeedback(score){ document.getElementById("total") total.innerHTML = 'Well done, your score was... ' + score } The showFeedback function above uses the element with the id total and replaces the HTML content of this element with "Well done, your score was... followed by the contents of the score variable. The score variable is automatically converted into a string before it is concatenated with the rest of the text. If you have any questions, please add them to the comments section and I or another facilitator will do our best to answer them. Finishing Touches 62 comments In the previous step you added up the correct questions on your climate change quiz page and changed the HTML to show the score to the visitor. Now you are going to see how more JavaScript can be added, to make your quiz page more appealing to your audience. Adding to a function The showFeedback function that you will create in this step will make the results of the quiz more appealing for the visitor, because it will: Hide the Quiz element Change the HTML in the to give some feedback, including the user’s score Add an image that will appear in the function showFeedback(score){ document.forms.Quiz.style.display = "none"; body = document.getElementsByTagName("body") body.innerHTML = '

Well done, your score was... ' + score body.innerHTML += '
' } The showFeedback function sets the display attribute of the quiz to "none", hiding all the quiz questions. The function then changes the content of the tag to display the text Well done, your score was... followed by the user’s score. The final line of the function uses the += operator to add some more HTML to the body of the webpage. In this case, the additional HTML will show an image of fireworks that I have previously uploaded and stored on Trinket; you will need to replace this with an image of your own. Take the showFeedback function from the JavaScript above and use it in your quiz. You may need to edit it to refer to the correct elements in your HTML. Different feedback You can change the feedback a visitor gets when they submit their answers, to tell them they need to study the home page further, or to let them know if they have done well and achieved high marks. I have added conditional statements to my showFeedback function in the JavaScript below to give different feedback depending on the value of the score variable. if (score == "0"){ body.innerHTML = '

Do better next time, your score was... ' + score; } else if (score < "2"){ body.innerHTML = '

Maybe you need to visit the home page again, your score was... ' + score; } else if (score < "4"){ body.innerHTML = '

You did well but there is room for improvement, your score was... ' + score; } else if (score < "6"){ body.innerHTML = '

You almost got full marks! Great, your score was... ' + score; } else { body.innerHTML = '

Excellent, full marks to you! Your score was... ' + score; } To make your climate change website more personalised for your visitor, add your own feedback to your quiz. Share the link to your climate change Trinket with your fellow learners in the comments below. Look at the other learners’ Trinkets and comment on anything you’ve spotted that you would like to use on your own website. Application Programming Interfaces (API) 51 comments Well done! You have built your climate change website and have used HTML, CSS, and JavaScript. In this step you are going to learn about APIs and how they can be integrated into your website. An API enables a web developer to integrate content from external websites into their own webpage; the API makes it easy to share content from one website to another. You may have seen Instagram, Facebook, Twitter, and Met Office weather information on other websites than their own. The development of APIs APIs were first developed to integrate shopping websites such as Amazon and eBay within external websites. Amazon and eBay allowed other websites to search and display products that were hosted on their own web servers. As the number of people viewing their products increased, so did their sales. APIs became more social with photo-sharing sites, Facebook, and Twitter all creating their own APIs to increase their presence on other websites. Maps You can use map APIs from Google and Bing to show a large amount of information that is not stored on your own web server. By using the Google Maps API, a visitor to your website can take control of the map and use features that Google have developed, such as changing map views, adding pins, navigating to a different location, and zooming in to a specific point. This Trinket shows a Google Map indicating the location of China. An alert stating “This page can’t load Google Maps correctly” and a “For development purposes only” watermark both appear, because you have to sign up for an API key to get the full functionality — more about this later. For the purpose of this example, so that you can view the JavaScript and HTML at the same time, I have put some JavaScript inside the

Customising the JavaScript

The mapProp variable in the myMap function in the JavaScript determines what the map will display, using a latitude and longitude for the centre, and also the level of zoom. You can change the map to show a location you have referred to on your climate change webpage.

Add the JavaScript from above into your webpage, either in your script.js or directly into your HTML.
Use this webpage to find the latitude and longitude of the location you want to display.
Change the centre in the JavaScript to the latitude and longitude you have found.
Change the zoom value to be appropriate for the area you want to show.

Adding more interactivity

This Trinket demonstrates how the Google Maps API can be used when combined with your own website. The Trinket uses concepts from this course to allow a user to enter latitude and longitude coordinates to recentre the map.

Read through the code. Can you identify how it works? Markers

Using the Google Maps API enables you to customise features of the map, for example by placing a marker to show a location you are referring to on your webpage. Markers are designed to be interactive, allowing a user to click on a marker to show an information window displaying further information. You can customise markers by adding animation, changing the image, and adding an icon. Further information about using markers can be found here. API keys

In this step you have been using a URL without an API key; this is the reason for the appearance of the alert from Google and the watermark “For development purposes only”.

An API key is used by the service you are using to track how the API is being used. API keys can also record what time of day the API is being accessed, and where in the world it is being used. Some APIs are free to use, but others will use the API key to keep track of usage so that they can charge the person or company who signed up for that API key. Moving on

Well done! You have nearly completed the final week of the course; all that’s left is the peer assessment. In the next step you will use the HTML, CSS, and JavaScript that you have learnt during the course to create a website that will be peer-assessed by the other learners on the course.