├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── guides
├── README.md
├── flash-example
│ ├── MayYourBladeBanner468x60_v2.fla
│ ├── MayYourBladeBanner468x60_v2.html
│ └── MayYourBladeBanner468x60_v2.swf
├── images
│ ├── 10a.jpg
│ ├── 10b.jpg
│ ├── 2b.jpg
│ ├── 4a.jpg
│ ├── 4b.png
│ ├── 4c.png
│ ├── 5a.png
│ ├── 6a.gif
│ ├── 6b.png
│ ├── 6c.png
│ ├── 7a.png
│ ├── 8a.png
│ ├── 8b.png
│ ├── 8c.png
│ ├── browser-and-editor.png
│ ├── browser-console.png
│ ├── duck.jpg
│ ├── kitten.jpg
│ └── web-directory.jpg
├── index.html
├── javascript-examples
│ ├── basic-canvas.html
│ ├── canvas-loop.html
│ ├── conditional.html
│ ├── data-output-loop.html
│ ├── firefox-logo.png
│ ├── function.html
│ ├── hello.html
│ ├── javascript-gradient-image.html
│ ├── javascript-sinewave-circles.html
│ ├── javascript-sinewave-squares.html
│ ├── multiply-numbers-blur.html
│ ├── multiply-numbers-click.html
│ ├── number-guessing-game.html
│ ├── shopping-list.html
│ ├── sinewave-function.html
│ ├── template.html
│ └── text-search.html
├── lesson1.html
├── lesson2.html
├── lesson3.html
├── lesson4.html
├── lesson5.html
├── lesson6.html
├── lesson7.html
├── lesson8.html
├── prism
│ ├── prism.css
│ └── prism.js
└── style.css
├── index.html
├── l10n
├── en
│ └── .gitkeep
├── es
│ └── .gitkeep
└── fr
│ └── .gitkeep
├── slide-script
└── index.html
└── slides
├── License.md
├── Readme.md
├── index.html
├── pictures
├── cover.jpg
├── dom.jpg
├── logo.svg
└── picture.jpg
└── shower
├── License.md
├── Readme.md
├── shower.min.js
└── themes
├── bright
├── License.md
├── Readme.md
├── fonts
│ ├── Anka.Coder.Italic.woff
│ ├── Anka.Coder.woff
│ ├── OpenSans.Bold.Italic.woff
│ ├── OpenSans.Bold.woff
│ ├── OpenSans.Italic.woff
│ ├── OpenSans.Light.woff
│ └── OpenSans.woff
├── images
│ ├── grid-16x10.svg
│ └── grid-4x3.svg
├── index.html
├── pictures
│ ├── exact.png
│ ├── square.png
│ ├── tall.png
│ └── wide.png
└── styles
│ └── screen.css
└── ribbon
├── License.md
├── Readme.md
├── fonts
├── PTMono.woff
├── PTSans.Bold.Italic.woff
├── PTSans.Bold.woff
├── PTSans.Italic.woff
├── PTSans.Narrow.Bold.woff
└── PTSans.woff
├── images
├── grid-16x10.svg
├── grid-4x3.svg
├── linen.png
├── linen@2x.png
└── ribbon.svg
├── index.html
├── pictures
├── exact.png
├── square.png
├── tall.png
└── wide.png
└── styles
└── screen.css
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Community Participation Guidelines
2 |
3 | This repository is governed by Mozilla's code of conduct and etiquette guidelines.
4 | For more details, please read the
5 | [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/).
6 |
7 | ## How to Report
8 | For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.
9 |
10 |
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | CC0 1.0 Universal
2 |
3 | Statement of Purpose
4 |
5 | The laws of most jurisdictions throughout the world automatically confer
6 | exclusive Copyright and Related Rights (defined below) upon the creator and
7 | subsequent owner(s) (each and all, an "owner") of an original work of
8 | authorship and/or a database (each, a "Work").
9 |
10 | Certain owners wish to permanently relinquish those rights to a Work for the
11 | purpose of contributing to a commons of creative, cultural and scientific
12 | works ("Commons") that the public can reliably and without fear of later
13 | claims of infringement build upon, modify, incorporate in other works, reuse
14 | and redistribute as freely as possible in any form whatsoever and for any
15 | purposes, including without limitation commercial purposes. These owners may
16 | contribute to the Commons to promote the ideal of a free culture and the
17 | further production of creative, cultural and scientific works, or to gain
18 | reputation or greater distribution for their Work in part through the use and
19 | efforts of others.
20 |
21 | For these and/or other purposes and motivations, and without any expectation
22 | of additional consideration or compensation, the person associating CC0 with a
23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
25 | and publicly distribute the Work under its terms, with knowledge of his or her
26 | Copyright and Related Rights in the Work and the meaning and intended legal
27 | effect of CC0 on those rights.
28 |
29 | 1. Copyright and Related Rights. A Work made available under CC0 may be
30 | protected by copyright and related or neighboring rights ("Copyright and
31 | Related Rights"). Copyright and Related Rights include, but are not limited
32 | to, the following:
33 |
34 | i. the right to reproduce, adapt, distribute, perform, display, communicate,
35 | and translate a Work;
36 |
37 | ii. moral rights retained by the original author(s) and/or performer(s);
38 |
39 | iii. publicity and privacy rights pertaining to a person's image or likeness
40 | depicted in a Work;
41 |
42 | iv. rights protecting against unfair competition in regards to a Work,
43 | subject to the limitations in paragraph 4(a), below;
44 |
45 | v. rights protecting the extraction, dissemination, use and reuse of data in
46 | a Work;
47 |
48 | vi. database rights (such as those arising under Directive 96/9/EC of the
49 | European Parliament and of the Council of 11 March 1996 on the legal
50 | protection of databases, and under any national implementation thereof,
51 | including any amended or successor version of such directive); and
52 |
53 | vii. other similar, equivalent or corresponding rights throughout the world
54 | based on applicable law or treaty, and any national implementations thereof.
55 |
56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of,
57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
59 | and Related Rights and associated claims and causes of action, whether now
60 | known or unknown (including existing as well as future claims and causes of
61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum
62 | duration provided by applicable law or treaty (including future time
63 | extensions), (iii) in any current or future medium and for any number of
64 | copies, and (iv) for any purpose whatsoever, including without limitation
65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
66 | the Waiver for the benefit of each member of the public at large and to the
67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver
68 | shall not be subject to revocation, rescission, cancellation, termination, or
69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work
70 | by the public as contemplated by Affirmer's express Statement of Purpose.
71 |
72 | 3. Public License Fallback. Should any part of the Waiver for any reason be
73 | judged legally invalid or ineffective under applicable law, then the Waiver
74 | shall be preserved to the maximum extent permitted taking into account
75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
76 | is so judged Affirmer hereby grants to each affected person a royalty-free,
77 | non transferable, non sublicensable, non exclusive, irrevocable and
78 | unconditional license to exercise Affirmer's Copyright and Related Rights in
79 | the Work (i) in all territories worldwide, (ii) for the maximum duration
80 | provided by applicable law or treaty (including future time extensions), (iii)
81 | in any current or future medium and for any number of copies, and (iv) for any
82 | purpose whatsoever, including without limitation commercial, advertising or
83 | promotional purposes (the "License"). The License shall be deemed effective as
84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the
85 | License for any reason be judged legally invalid or ineffective under
86 | applicable law, such partial invalidity or ineffectiveness shall not
87 | invalidate the remainder of the License, and in such case Affirmer hereby
88 | affirms that he or she will not (i) exercise any of his or her remaining
89 | Copyright and Related Rights in the Work or (ii) assert any associated claims
90 | and causes of action with respect to the Work, in either case contrary to
91 | Affirmer's express Statement of Purpose.
92 |
93 | 4. Limitations and Disclaimers.
94 |
95 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
96 | surrendered, licensed or otherwise affected by this document.
97 |
98 | b. Affirmer offers the Work as-is and makes no representations or warranties
99 | of any kind concerning the Work, express, implied, statutory or otherwise,
100 | including without limitation warranties of title, merchantability, fitness
101 | for a particular purpose, non infringement, or the absence of latent or
102 | other defects, accuracy, or the present or absence of errors, whether or not
103 | discoverable, all to the greatest extent permissible under applicable law.
104 |
105 | c. Affirmer disclaims responsibility for clearing rights of other persons
106 | that may apply to the Work or any use thereof, including without limitation
107 | any person's Copyright and Related Rights in the Work. Further, Affirmer
108 | disclaims responsibility for obtaining any necessary consents, permissions
109 | or other rights required for any use of the Work.
110 |
111 | d. Affirmer understands and acknowledges that Creative Commons is not a
112 | party to this document and has no duty or obligation with respect to this
113 | CC0 or use of the Work.
114 |
115 | For more information, please see
116 |
117 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Beginning Programming Content Kit
2 | Hello and welcome to the "Beginners programming" Content Kit. This kit contains resources that you can use the learn and teach general programming principles and the JavaScript language.
3 |
4 | To get started please go to [the start page](index.html).
5 |
--------------------------------------------------------------------------------
/guides/README.md:
--------------------------------------------------------------------------------
1 | beginning-coding
2 | ================
3 |
4 | This is a repository for the source code behind the " Introduction to programming: Beginning your journey towards learning to code" course that is currently live at http://people.mozilla.org/~cmills/coding-beginners/
5 |
--------------------------------------------------------------------------------
/guides/flash-example/MayYourBladeBanner468x60_v2.fla:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mdn/beginning-programming-content-kit/dae1fbbc51e5b485d55c8df901abe29243f4cb3c/guides/flash-example/MayYourBladeBanner468x60_v2.fla
--------------------------------------------------------------------------------
/guides/flash-example/MayYourBladeBanner468x60_v2.html:
--------------------------------------------------------------------------------
1 |
2 |
Our world is becoming increasingly controlled by computers, and you will come into contact with code and computer systems every day, most of the time not even realising it! For many of us, code is like voodoo, or black magic, and this is partially true - complex computer systems require complex code to control them. But understanding the basic principles and building blocks that underpin pretty much all programming languages is well with the grasp of all of us: really! In this course, I will take you gently through all the programming fundamentals you'll need to grasp a working understanding on how code and computer systems work, and even write some simple programs yourself.
31 |
32 |
Introduction
33 |
34 |
This is a basic course, aimed at people with no previous development/programming experience, which aims to teach the fundamentals of how systems work, and the very basics of how to program. The course uses JavaScript — the programming language that powers the Web — as the language for demonstrating all the taught concepts, but these concepts are shared across most programming languages.
35 |
36 |
To take part in this course, you just need access to a computer with a web browser and a text editor installed on it.
A computer. Internet access is useful, as there are a number of resources linked from these notes that aren't accessible when you are offline, but it isn't essential for you to follow along with this course.
44 |
At least one decent web browser installed: Any of the following are ok:
45 |
Recommended text editor: Any text editor is ok, as long as it is a pure text editor (Word and Open Office are not appropriate) that supports UTF-8 (NotePad is not ok). Sublime Text has a free trial available, for all platforms, and is excellent. Other free alternatives include:
54 |
A huge amount of software exists in the world, controlling the systems that enrich our lives. Some code is really obvious, such as operating systems like Windows, web sites, and video games. Some is not so obvious, for example the embedded code that controls our microwave, our thermostat, or our car engine.
32 |
33 |
The exact format, syntax and usage of different types of code differs greatly, but most share fundamental structures and concepts. In this course, we'll aim to teach you these fundamentals. The particular type of code we'll use in this course is JavaScript, the programming language that powers many web sites and applications. We've chosen this one because it is readily available, and very easy to demonstrate tangible results with, but the aim here is not really to just teach you JavaScript, but to teach you the underlying principles that apply to pretty much every programming language.
34 |
35 |
What are we doing when we write code?
36 |
37 |
Regardless of what type of code we write, we write it to control computer systems: this could be because we want to find more information about those systems, give them information/data to process, or give them instructions. In the same way that we can use a language like English, German or Chinese to ask a person questions and give them instructions, we can use a language like JavaScript to ask computers questions and give them instructions.
38 |
39 |
The computer has to take in this code in some way, read it, and then do something as a result. For the computer to understand the code, it has to be written in the right syntax: the structure of any language is important, for making yourself understood. The syntax of English and other human languages is verbs, nouns, adjectives, etc. The syntax of JavaScript is variables, functions, loops, etc.
40 |
41 |
The computer will have a piece of software that reads the code you write, works out what to do with it, and then returns a result. This is often called an interpreter, or an engine perhaps. In the case of JavaScript, the interpreter is the web browser you are using. A web browser downloads web pages, interprets the code contained within them (which will usually include some JavaScript), and gives you a web page to look at.
42 |
43 |
Note:: To make sense of this, let's have a quick look at my javascript-gradient-image.html example. This simply creates a drawing canvas on the page using the HTML <canvas> element, then uses JavaScript to place some pixels on the canvas, in this case, a circle filled with a colour gradient, and a copy of the Firefox logo, which it grabs out of an image file. You can view the source of the example by right clicking/Cmd + clicking on the page and selecting the "View Source" or "source" option.
44 |
45 |
Compiler: Some languages also need a compiler to run: an application that turns code into a package that can then be run to create an output. Flash is an example of a compiled language — you create some Flash source code, then compile it into a Flash Movie. A web browser with the Flash Player plugin installed can then display this Flash movie, which is its own standalone little block; the source code is no longer readable.
46 |
47 |
Note: Let's now look at a Flash example to see how this works. Open up our flash example, which is an old advertising banner for an old metal band. If you try to "View source" on the banner, you won't be able to: the code is compiled and locked away.
48 |
49 |
Interpreted languages are often easier to learn than compiled languages, because with interpreted languages you can just open up the source code and see how it works. You can't do that with compiled languages because the language is converted into a non-human readable form when compiled.
50 |
51 |
A quick course in Web
52 |
53 |
The web works like so: when you type a web address into your browser, it sends a request to the server that the web site is stored on. The server then sends the files that comprise the web page back to the web browser, which is on the client, aka your computer.
54 |
55 |
56 |
Client-side languages are languages that are sent to the client, then processed (interpreted and displayed). JavaScript is a client-side language.
57 |
Server-side languages are languages that are processed on the server before the result is then sent to the client and displayed. Example: PHP.
58 |
59 |
60 |
Server-side and client languages are no better than each other; they have different uses on the Web. Client-side is for displaying and interacting with content; server-side is more for storing data, and providing the right data to the client, based on instructions it is given. For example, when you look at Amazon, you are not looking at a different page every time you look at a product. You are looking at the same page, but with different information inserted into it. when you search for a product using the interface displayed to you on the client-side, a query is sent to a database on the server-side, and server-side technologies find and retrieve the correct data that matches your search, and sends it back to the client to be displayed on the page.
61 |
62 |
63 |
Fundamentals of working with code
64 |
65 |
In this course we'll be using a basic template file to manipulate and view the results of our code. Let's have a look at this sample file now, and explain some code basics.
66 |
67 |
The file is inside this Topic kit at guides/javascript-programming/template.html. Find it and open it in your text editor, and Open it in your browser too. You should end up with something a bit like this:
68 |
69 |
70 |
71 |
The rendered code view inside the browser doesn't look like much right now. You've just got a line of text coloured red. The source code view inside the text editor reveals a lot more however — you'll see a whole bunch of code that you can add to, to make the code do more interesting things.
72 |
73 |
It is recommended that before working on each new example, you make a new copy of the template.html file to write your code into. Close the original template file, make a copy now and put it somewhere easy to find, and open it up again in both text editor and browser.
74 |
75 |
Leave the original intact so that you've always got it to refer to.
76 |
77 |
HTML
78 |
79 |
HTML stands for HyperText Markup Language, and it is the language we use on the Web to add structure and meaning to website content/data. For the purposes of this course, we'll get you to add any HTML you need to write into the indicated section:
80 |
81 |
<!-- ANY HTML YOU WRITE GOES BETWEEN THIS COMMENT, AND THE END HTML
82 | COMMENT BELOW. DO NOT PUT ANY HTML OUTSIDE THESE BOUNDARIES UNLESS YOU
83 | KNOW WHAT YOU ARE DOING. AN HTML HEADING IS INCLUDED TO GIVE YOU
84 | AN IDEA. -->
85 |
86 | <h1>Example heading</h1>
87 |
88 | <!-- END HTML -->
89 |
90 |
The uppercase text surrounded by the <!-- and --> are HTML comments: these are ignored by browsers and can be used to include comments in your work to help you (and others) understand what is going on in your code. In this case we are providing boundaries for your to write your HTML into, so if you are completely new to this, you will be less likely to break anything.
91 |
92 |
We have included one HTML element to start you off: <h1>Example heading</h1>. This is an HTML heading element: wrapping any text in an opening <h1> tag and a closing </h1> tag will make that text into the top level heading (or main title) of your site.
93 |
94 |
95 |
Exercise: Adding some more HTML
96 |
try adding another HTML element just below the existing one, then save the page and refresh the browser:
97 |
98 |
<p>I am a paragraph.</p>
99 |
100 |
101 |
Note: For more on the basics of HTML, read HTML basics.
102 |
103 |
CSS
104 |
105 |
CSS stands for Cascading Style Sheets, and it is the language we use on the Web to style HTML content — to getting it looking how you want. For the purposes of this course, we'll get you to add any CSS you need to write into the indicated section:
106 |
107 |
/* ANY CSS THAT YOU WRITE GOES BETWEEN THIS COMMENT, AND THE END CSS
108 | COMMENT BELOW. DO NOT PUT ANY CSS ABOVE THE <style> OR BELOW THE
109 | </style> tag! AN EXAMPLE IS INCLUDED TO GIVE YOU AN IDEA. */
110 |
111 | h1 {
112 | color: red;
113 | }
114 |
115 | /* END CSS */
116 |
117 |
The uppercase text surrounded by the /* and */ are CSS comments, which look different but have the same purpose/effect as HTML comments. These are boundaries for your to write your CSS into.
118 |
119 |
We have included one CSS rule to start you off: h1 { color: red; }. This selects our <h1> element and changes the value of its color property to red, which has the effect of turning the text color red.
120 |
121 |
122 |
Exercise: More CSS
123 |
Try changing red to blue, saving the page and refreshing the browser.
124 |
125 |
Now try adding a second CSS rule to select the paragraph you added in the last section, under the first one:
This shows usage of multiple lines of CSS in the same rule.
135 |
136 |
137 |
Note: For more on the basics of CSS, read CSS basics.
138 |
139 |
JavaScript
140 |
141 |
JavaScript is the language we use to program dynamic functionality on the Web. For the purposes of this course, we'll get you to add any JavaScript you need to write into the indicated section:
142 |
143 |
//ANY JAVASCRIPT YOU WRITE GOES BETWEEN THIS COMMENT, AND THE END
144 | //JAVASCRIPT COMMENT BELOW. DO NOT PUT ANY JAVASCRIPT OUTSIDE THESE
145 | //BOUNDARIES UNLESS YOU KNOW WHAT YOU ARE DOING. SOME SIMPLE JAVASCRIPT
146 | //IS INCLUDED TO GIVE YOU AN IDEA.
147 |
148 | console.log('JavaScript test!');
149 |
150 | // END JAVASCRIPT
151 |
152 |
JavaScript comment lines start with a double forward slash — //. We have provided these as boundaries for you to write your JavaScript into.
153 |
154 |
155 |
Exercise: Playing with JavaScript using browser developer tools
156 |
We have included one JavaScript line to start you off: console.log('JavaScript test!');. This writes a message into your browser's developer console, accessed by pressing Ctrl + Shift + I (Cmd + Opt + I on Mac OSX, F12 on Internet Explorer) and clicking on the Console tab. Have a look now: you should see something like this:
157 |
158 |
159 |
160 |
Note: The browser developer console is a really useful tool for trying things out, and debugging your code when it isn't working as it should be. Make sure you are familiar with it — discover browser developer tools is a good place to start.
161 |
162 |
Now let's try adding a second JavaScript line underneath the first one:
If you include this in your code, save it in the text editor and then refresh the browser, you'll see that we've updated the contents of our heading using JavaScript.
Now on to the interesting stuff! We'll now have a look at the programming basics that exist in pretty much every programming language, in one form or another. Before starting this section, make a new copy of the template.html file and open it in your browser and text editor.
33 |
34 |
Variable basics
35 |
36 |
Variables are containers that allow you to store something that you want to use later on, be that a simple name or age value, or something more complicated. Why would you want to do this? Let's look at a simple program that says hello to you: See my Hello example (don't look at the source code!)
37 |
38 |
Without variables, it would be impossible to create a personalised hello message. You'd just have to stick to "Hello there.", which would be really boring. So variables are all about allowing us to create programs that dynamically change depending on things that differ as the program is being used, such as the user using the program, the date and time of day, the weather, and so on. Programming is pretty much impossible without variables.
39 |
40 |
To use a variable, we first have to declare it — we say "I am making this variable exist. Its name is x, and its initial value is y."
41 |
42 |
A really simple code example:
43 |
44 |
var myHairColor = "brown";
45 | // Note the quotes; these can be single or double quotes;
46 | //your choice, as long as you are consistent
47 |
48 |
You could also then change a variable later on, once it is declared.
49 |
50 |
var myHairColor = "brown";
51 | // declare a variable myHairColor, with an initial value of "brown"
52 |
53 | myHairColor = "red";
54 | // change the existing variable myHairColor's value to "red"
55 |
56 |
A few more simple examples follow:
57 |
58 |
var myName = "Chris";
59 | // A string
60 | // Also note that JavaScript is case sensitive, so myname is
61 | // a different variable to myName
62 |
63 | var myAge = 35; // a number
64 | var haveKids = true; // a boolean
65 | var favouriteThings = ['raindrops','kettles','packages','ponies'] // an array
66 |
67 |
68 |
Exercise: Proving how variables exist and are stored
69 |
70 |
As a quick exercise, let's go into the browser developer console and try accessing a new variable the console pane (the console is basically a way to access the internal state of the code or application). To open the console, press Ctrl + Shift + I; Cmd + Opt + I on Mac OSX; F12 on Internet Explorer, and click the console tab.
71 |
72 |
To call or access a variable, you just use the variable name. Enter this into the console:
73 |
74 |
myCar
75 |
76 |
This should give you a result of undefined, because the variable doesn't yet exist.
77 |
78 |
Let's try declaring the variable: type the following into the console:
79 |
80 |
var myCar = "Citroen";
81 |
82 |
and then trying this again in the console:
83 |
84 |
myCar
85 |
86 |
The console should now return the variable's value to you.
87 |
88 |
89 |
90 |
When we have a value stored in a variable, we can use it in our program by simply saying the variable name again. Let's look at something slightly more complex that actually does something interesting. The prompt function opens up a dialog box asking the user to enter a value into a text box. When they have done so, it stores that value in a variable:
91 |
92 |
var myHairColor = prompt("Enter your hair color");
93 | // Ask the user for their hair color
94 |
95 |
You can then choose to do something else with that value:
96 |
97 |
alert("Chris has " + myHairColor + " hair.");
98 | // display a personalised message about hair colour
99 |
100 |
alert is a simple function that pings up a dialog box containing whatever message you include inside it, in this case Chris has " + myHairColor + " hair.".
101 |
102 |
This string of text may look strange, and we'll explain it better later on. For now, let's just say that we are gluing together three things:
103 |
104 |
105 |
The text "Chris has "
106 |
The current value inside the myHairColor variable
107 |
The text " hair."
108 |
109 |
110 |
A lot of programming involves gluing different things together to get the output you want.
111 |
112 |
113 |
Exercise: write the hello example from before
114 |
The hello example that we checked out at the very start of this section is very similar in the way that it works to the hair colour example we just studied. I'd like you to try writing the hello example into your working template file, and then run it to get it working. DON'T look at the source code unless you get stuck!
115 |
116 |
117 |
Variable types
118 |
119 |
In JavaScript, different variables have different assigned types:
120 |
121 |
122 |
Strings contain strings of text. The presence of quote marks makes them a string. If you didn't use quote marks, you would get an error, because the browser would think the variable value was not a string, but another variable name instead.
123 |
Integers contain numbers, which don't need quote marks.
124 |
Booleans contain true/false values. These are very useful when creating program logic, as you'll see later.
125 |
Arrays contain multiple values at once; these are very useful for containing multiple related values that you want to manipulate in a similar way.
126 |
127 |
128 |
Exercise: finding the types of variables
129 |
130 |
Let's see if I'm telling the truth. In the JavaScript section of your template file, enter the following block of code, then save, then refresh the browser:
131 |
132 |
var myHairColor = "brown";
133 | // This is a string
134 |
135 | var myAge = 35;
136 | // This is an integer
137 |
138 | var haveKids = true;
139 | // This is a boolean
140 |
141 | var faveFoods = ["Coco Pops", "Fajitas", "Curry", "Bacon"];
142 | // This is an array
143 |
144 |
Then in the browser console, try outputting the type of each variable, using the typeof operator, like this:
145 |
146 |
typeof myHairColor;
147 | // Return the variable type of the myHairColor variable
148 |
149 |
What do you get when you try this on an array?
150 |
151 |
152 |
An aside on JavaScript syntax
153 |
154 |
Before we go much further, we ought to dwell on some simple but important syntax rules. A slightly more complex example might look like so:
155 |
156 |
var squareArea = function(w,h) {
157 | // This is a function stored in a variable;
158 | //we'll look at these more later
159 | var result = w * h;
160 | // Here we are multiplying the w and h arguments together and
161 | //storing them in a variable called result
162 | alert(result);
163 | // Now we are printing the result variable into a dialog box
164 | // on the screen.
165 | };
166 |
167 |
168 |
The var keyword is used to declare a variable; make it exist in the first place.
169 |
The next bit is the variable name, which can be almost anything of your choosing, but with a few restrictions. You can't use numbers at the start, and you can't use spaces, punctuation or reserved characters anywhere. You are also advised to use easy to remember, simple names, not too long and not too short. Above I've used lower camel case, first word lower case, and subsequent words capitalised and joined onto the end. This makes your variables easy to read and not too complex to type.
170 |
The next bit is an equals sign, which means "we are making the bit of the left equal to the bit of the right." In this case we are making squareArea equal a function that multiplies two numbers together. This is also called the assignment operator; more on operators below.
171 |
The final bit of the variable is whatever you want to store inside the variable — in this case an entire function.
172 |
173 |
174 |
The curly braces — { … } — are very important in JavaScript. These signify the start and end of a block of code that is all related, and is run together according to a set condition or action (e.g. when a user presses a button, or when a variable holds a certain value.) For each open curly brace, there MUST be a closed curly brace, otherwise the program won't work.
175 |
176 |
The semi colons (;) are also important. These signify the end of one instruction and where another one starts. Without these, the program probably won't work as expected
177 |
178 |
Also note that whitespace doesn't matter much to JavaScript, except inside strings and as a separator for values, keywords, etc. All the whitespace in your code is basically just there to make the code more readable. So
179 |
180 |
var myName;
181 |
182 | var yourName;
183 |
184 |
Is equivalent to
185 |
186 |
var MyName;var yourName;
187 |
188 |
Operators
189 |
190 |
In programming you'll meet many operators that you can use for calculations and comparisons. We've already seen a couple, such as = and typeof, and I've provided a more complete list of JavaScript's common operators below for reference. We won't laboriously go through all of these, just a few to give you an idea. We'll see examples of others as we move through the course.
191 |
192 |
193 |
+ : the concatenation or addition operator, depending on what it is used on
194 |
* : the multiplication operator
195 |
/ : the division operator
196 |
- : the subtraction operator
197 |
% : the modulus operator; returns the remainder of one number being divided by another
198 |
= : the assignment operator
199 |
== : the equality operator (don't use this)
200 |
===: the strict equality operator (use this instead)
201 |
|| : the or operator
202 |
&& : the and operator
203 |
! : the not operator
204 |
205 |
206 |
207 |
Exercise: making use of JavaScript operators
208 |
209 |
Let's play with a few operators. Try putting each of the below lines into the browser console to see what happens:
210 |
211 |
var myHairColor = "brown";
212 |
213 | "My hair color is " + myHairColor;
214 | // Join together the string specified in this line, and the one stored in myHairColor
215 |
216 |
var myAge = 34;
217 |
218 | myAge + 26;
219 | // Add together two numbers
220 |
221 |
var num1 = "34";
222 |
223 | var num2 = "26";
224 |
225 | num1 + num2;
226 | // Add together two strings?
227 |
228 |
What did the third code block give you? Not what you expected? Why is this?
229 |
230 |
Note: you can change the variable type of your variables with various built in JavaScript functions, for example keep num1 and num2 as strings above, and try the following.
231 |
232 |
Number(num1) + Number(num2);
233 |
234 |
Let's try some other examples, e.g.
235 |
236 |
8 % 2;
237 |
238 | 8 + 4 / 3 * 4;
239 |
240 |
The last example is interesting - does it give you the result you were expecting? (I would expect the result to be 1!) JS uses operator precedence to dictate what order the different parts of the equation will be executed in. If it is not turning out like you'd hoped, you can always add brackets to force the order, for example:
In general, to do useful things with programming languages, you need to grab an item you want to do something to, and then use code to do something to it.
33 |
34 |
In JavaScript, we do this by grabbing a reference to the object we want to have an effect on. We've already done this — we've stored some items in variables. You can store anything in a variable, whether it is a simple string or number value, or something more complicated, like a video, paragraph or other element on a web page. This is done via the document object model.
35 |
36 |
Making a start
37 |
38 |
For this section, make a new copy of the template file. Put the following HTML into your HTML area:
39 |
40 |
<h1 class="myHeading">My heading</h1>
41 |
42 |
We can grab a reference to this element using the following line — put this in your JavaScript area:
43 |
44 |
var myH1 = document.querySelector('.myHeading');
45 | // Store a reference to the h1 element inside a variable called myH1
46 |
47 |
We could then do things to our heading by affecting the variable with more JavaScript. For example, to alter the text inside the heading, you could do this:
48 |
49 |
myH1.innerHTML = "My updated heading";
50 | // Change the content inside our h1 to equal the specified string
51 |
52 |
53 |
54 |
Exercise: improving our game to make things happen in the HTML
55 |
56 |
Let's improve the user experience of our game. It is pretty bad form to have all your messages appearing in alert dialog boxes. This isn't something you want to see people using in the real world. It'd be better to have the messages appearing inside your web page. The current code looks like this:
At this point, open up the template file copy that you wrote the game code into previously. If you haven't got a copy, just create a new copy of the template and paste the above code into the JavaScript section.
77 |
78 |
79 |
To do this, we need to first create some HTML elements for the previous guesses, result of the last guess, and whether it is too low or too high. Add the following into your HTML area:
Now we need to store these in variables so we can get at them and do things with them in JavaScript. Add the following lines into the top of your JavaScript area:
87 |
88 |
var guesses = document.querySelector(".guesses");
89 | var lastResult = document.querySelector(".lastResult");
90 | var lowOrHi = document.querySelector(".lowOrHi");
91 |
92 |
Next we need to replace the alert() functions with lines to write the results into those paragraphs, not just shout them out in alert boxes. First, find the line var userGuess = prompt("Enter guess " + i);; directly below this line add the following:
93 |
94 |
guesses.innerHTML += userGuess + " ";
95 |
96 |
Now replace the line alert("Congratulations. You got it right!"); with
97 |
98 |
lastResult.innerHTML = "Congratulations! You got it right!";
99 | lowOrHi.innerHTML = "";
One of the best way to see instant results with JavaScript is by writing some simple HTML5 <canvas> examples. Canvas is a technology that allows you to use JavaScript to draw a bitmap image, which can then be manipulated/changed.
33 |
34 |
To do something with a canvas, you first have create one on your HTML page, like putting a picture frame on your wall.
35 |
36 |
Getting started
37 |
38 |
Make a new copy of the template file. Add the following to your HTML area:
39 |
40 |
<canvas width="500" height="500">
41 | </canvas>
42 |
43 | <!-- Create a canvas to draw on, 500 x 500 big.
44 | Note that HTML comments look different to
45 | JavaScript comments! -->
46 |
47 |
This creates a blank canvas 500 x 500 pixels big, ready for you to draw on.
48 |
49 |
To grab a reference to this canvas, we need to add two lines to our JavaScript area:
50 |
51 |
var myCanvas = document.querySelector('canvas');
52 | // Grab a reference to the canvas element
53 |
54 | var myContext = myCanvas.getContext('2d');
55 | // Create the context we will draw in
56 |
57 |
First of all we store a reference to the Canvas inside the myCanvas variable, in the same way as we saw above. Then we create a drawing context for our canvas, inside a myContext variable. Why did this take two steps? Well, 2d is not the only context you can draw in using canvas. There is also an experimental WebGL (3D context) that allows you to draw things into real 3D space, but we won't touch that here because it's way too complicated!
58 |
59 |
Next, let's draw a simple rectangle on our canvas — add these lines to the bottom of the JavaScript area:
60 |
61 |
myContext.fillStyle = 'rgba(0,0,255,0.5)';
62 | // What colour do we want to draw the rectangle?
63 |
64 | myContext.fillRect(0,0,200,200);
65 | // Draw the rectangle itself
66 |
67 |
Note: You can see this basic example running live in our Basic canvas page.
68 |
69 |
These two in-built functions are doing the following:
70 |
71 |
72 |
fillStyle: Sets the colour of whatever you decide to draw. In this case we are using an rgba value that defines a semi-transparent blue. the first three arguments inside the brackets are the amount of red, green and blue you want in your colour (values between 0 and 255), and the third value sets how transparent the colour is (values between 0 and 1).
73 |
fillRect: Sets the size and position of the rectangle. The first two arguments set the X and Y position of the top left hand corner of the rectangle, in this case the top left hand corner of the canvas, which is (0,0). The third and fourth arguments set the width and height of the rectangle, in pixels.
74 |
75 |
76 |
Have a play with drawing different rectangles and squares; adjust the values to see what happens. Try playing with these too:
77 |
78 |
myContext.strokeStyle = 'rgba(0,255,0,0.5)';
79 | // Set a colour for the stroke, which is the outer
80 | //bound of the rectangle.
81 |
82 | myContext.lineWidth = 1;
83 | // How thick do we want the stroke to be?
84 |
85 | myContext.strokeRect(200,200,50,50);
86 | // Draw an outline rectangle, not a solid colour
87 | //rectangle like before
88 |
89 |
Canvas loops
90 |
91 |
Lets look at some more complex loop examples with canvas. Type in the following, at the bottom of your JavaScipt area:
92 |
93 |
myContext.fillStyle = 'rgba(0,0,255,0.15)';
94 | for(i = 0; i <= 9; i++) {
95 | // start with variable i having the value 0. Run the loop
96 | // over and over again until i equals 9, increasing the value
97 | // of i by 1 after each time
98 | myContext.fillRect(i,i,25+i,25+i);
99 | }
100 |
101 |
Here we are setting a specific colour, then running a loop 10 times. Each time we run the loop, we draw a square that is slightly bigger, in a slightly different place. You can use this as a template for your experimentations in the next section (see Canvas loop for the example running live.)
102 |
103 |
104 |
105 |
Exercise: hacking your canvas loops
106 |
107 |
Let's try altering some of the code to make different effects.
108 |
109 |
110 |
Altering some other values of the square each time to loop runs by modifying them by i. For example, you could make the square bigger each time, by modifying the size by a multiple of i:
Start i and the square values bigger and use a minus iterator to make the square smaller each time: i-- instead of i++. But remember to alter the exit condition too, so you don't end up with an infinite loop!
115 |
116 |
Increase the value of the exit condition so the loop draws more squares.
117 |
118 |
Make the iterator itself bigger so the loop draws the squares further apart, for example i+=5, which is equivalent to i = i + 5 — "take the existing value of i and add 5 to it".
119 |
120 |
Define the square colour inside the loop and modify it by i too, for example:
Ok, so that looks quote horrible. the colour value is actually passed in as a string, so to construct the final string we want to pass in we've had to concatenate (glue together) a string of "rgba(0,0,", followed by the blue value created by multiplying i by 6 then adding 50, followed by a string of ",0.5)".
125 |
126 |
You could also try using random values; Try using say Math.floor(Math.random()*200) for one or more of the RGB colour values, for example.
127 |
128 |
129 |
Advanced loop ideas
130 |
131 |
How about rotating the squares? Canvas has a built-in rotate function, which unhelpfully takes a rotation value in radians. Just try playing with really small values; for example, try adding this at the bottom of your for loop (just before the closing curly brace (})):
132 |
133 |
myContext.rotate(0.025);
134 |
135 |
How about trigonometry? How about a sine wave of squares? Try something like this:
Or how about replacing our square with a circle? You can draw a circle using the arc() function, but this is a bit more complicated than before. To draw a circle you need to tell canvas to begin the drawing path with beginPath(), and then draw the circle using fill() (or stroke(), if you only want an outline circle; you'd have to use strokeStyle() to set the stroke colour in this case, not fillStyle()):
Further improving our guessing game with functions and events
24 |
25 |
26 |
31 |
32 |
Our game from earlier has still got a problem. We are still using a prompt() function to bring up a dialog box to ask players for guesses. This is still really bad for user experience. One of the core rules of user experience is to keep the number of pop ups down to a minimum. You all know how annoying popups can be. We should be able to do our entire app inside the web page, collecting data from the user with form elements. Our code currently looks like this:
Before running through the below steps, find the template file that you previously wrote your cgame code into. If you don't have it or can't find it, then no matter - you can create a new copy of the template and copy the code into it.
68 |
69 |
70 |
So first we need to provide a different way for the user to give us their guesses, given that we want to get rid of the prompt() function. The best way to collect information from users is to use <input> elements. In your HTML, add the following at the bottom of your </body> area.
Now we need to change our JavaScript so that in each turn of the game, the user's guess is taken from the submitted form, and not a prompt() function. This is trickier than you'd think, so I'll give you some clues:
79 |
80 |
81 |
You will need to get rid of the loop and instead encapsulate the guess processing code in a function
82 |
You will need to add an event listener that listens for the form being submitted (the button being clicked) and as a result runs the function
83 |
You will need a variable that tracks what guess number we are on and is incremented each time the function runs
84 |
After 10 guesses we need to end the game with some kind of "Game over" message
85 |
When the number is guessed correctly, the game should end and no more guesses should be allowed
86 |
87 |
88 |
89 |
90 |
91 |
92 |
Lets handle these, one at a time.
93 |
94 |
Get rid of the loop and instead encapsulate the guess processing code in a function
95 |
96 |
97 |
This requires us to replace the for loop line with a function
98 |
We also need to grab references to the relevant form elements in JavaScript
99 |
We also need to grab the guess from the value inside the form input element, not the prompt() function. You can grab the value inside a form input using its value property, so for example formElement.value.
100 |
101 |
102 |
To grab the form element references, enter the following variable definitions, beneath the existing ones:
103 |
104 |
105 | var guessSubmit = document.querySelector(".guessSubmit");
106 | // reference to the button that submits the guess
107 | var guessField = document.querySelector(".guessField");
108 | // reference to the text input field that the guess is typed into
109 |
110 |
Now replace the entire for loop with the following function:
111 |
112 |
function checkGuess() {
113 | // replace the for loop with a function
114 | var userGuess = Number(guessField.value);
115 | // no more prompt. The guess is now equal to the value inside
116 | // the input field when the function is run.
117 | guesses.innerHTML += userGuess + " ";
118 |
119 | if(userGuess === randomNumber) {
120 | lastResult.innerHTML = "Congratulations! You got it right!";
121 | lowOrHi.innerHTML = "";
122 | } else {
123 | lastResult.innerHTML = "Wrong!";
124 | if(userGuess < randomNumber) {
125 | lowOrHi.innerHTML = "Your guess is too low!";
126 | } else if(userGuess > randomNumber) {
127 | lowOrHi.innerHTML = "Your guess is too high!";
128 | }
129 |
130 | }
131 | }
132 |
133 |
Note the line var userGuess = Number(guessField.value);. This is what grabs the guess from the guessField value once the function is run. Note that we've also had to wrap it in a Number() function, to make sure the guess is treated like a number, not a string.
134 |
135 |
Add an event listener that listens to when the form is submitted (the button is clicked) and as a result runs the function
136 |
137 |
This is an easy step compared to all the changes we had to make before. Here we just need to add a line below the function that adds an onclick listener to the button that functions the function when the click happens.
138 |
139 |
Add this at the bottom of your JavaScript area:
140 |
141 |
guessSubmit.onclick = checkGuess;
142 |
143 |
Add a variable that tracks what guess number we are on and is incremented each time the function runs
144 |
145 |
Because we no longer have a loop, the guess number will no longer increment on its own. we need to emulate the loop functionality by first adding a variable that tracks the guess number. We then need to increase that value by one each time the checkGuess function is run.
146 |
147 |
Add this below the other variable definitions:
148 |
149 |
var guessCount = 1;
150 | // Add a variable that tracks the guess number we are on
151 |
152 |
Now add the following lines. These need to go at the bottom of the else { ... } code block (just above the seoncd-to-last closing curly brace), as we want to update the guess count each time the player gets the answer wrong:
153 |
154 |
guessCount++;
155 | // after each guess, increase the guess count
156 | guessField.value = "";
157 | // and empty the text input field ready for the next guess
158 |
159 |
The second line empties the form <input>element, ready for the player to enter the next guess.
160 |
161 |
After 10 guesses we need to end the game with some kind of "Game over" message
162 |
163 |
This is slightly trickier and requires us to add to our if ... else structure to check if the guessCount is equal to 10 or not. If so, we'll end the game with some kind of message. If not, we'll carry on with the code as it was before.
164 |
165 |
The existing if ... else structure looks like this:
166 |
167 |
if(userGuess === randomNumber) {
168 | lastResult.innerHTML = "Congratulations! You got it right!";
169 | lowOrHi.innerHTML = "";
170 | } else {
171 | lastResult.innerHTML = "Wrong!";
172 | if(userGuess < randomNumber) {
173 | lowOrHi.innerHTML = "Your guess is too low!";
174 | } else if(userGuess > randomNumber) {
175 | lowOrHi.innerHTML = "Your guess is too high!";
176 | }
177 |
178 | guessCount++;
179 | // after each guess, increase the guess count
180 | guessField.value = "";
181 | // and empty the text input field ready for the next guess
182 |
183 | }
184 |
185 |
You need to wrap all of this in the following additional if ... else structure:
186 |
187 |
if(guessCount === 10) {
188 | // if 10 guesses have been had
189 | lastResult.innerHTML = "!!!GAME OVER!!!";
190 | // provide a game over message
191 | } else {
192 |
193 | // place the existing if...else here
194 |
195 | }
196 |
197 |
If the game is over, then let the player know. If not, then carry on with the game.
198 |
199 |
When the number is guessed correctly, the game should end and no more guesses should be allowed.
200 |
201 |
This is a big issue: when the number is guessed correctly, we no longer want users to be able to enter more guesses, otherwise it totally breaks the flow of the game. There are a lot of different options that could be chosen to rectify this. We will add a function called disableForm() that stops the form being clickable when run. We will call this function when either the 10th guess is reached, or the number is guessed correctly.
202 |
203 |
first of all, add the disableForm() function somewhere near the bottom of the code. Just above the .onclick line will be fine:
204 |
205 |
function disableForm() {
206 | var wholeForm = document.querySelector(".form");
207 | // grab a reference to the whole form (the contents of the
208 | // div with class form)
209 | wholeForm.style.opacity = 0.5;
210 | // change the opacity of the form to 0.5
211 | guessField.setAttribute("disabled", "disabled");
212 | guessSubmit.setAttribute("disabled", "disabled");
213 | // disable the form field and submit button so they can
214 | // no longer be used
215 | }
216 |
217 |
Now invoke this function in appropriate places using disableForm(); — you want to invoke it if guessCount === 10, and if userGuess === randomNumber, to give you a large clue.
218 |
219 |
Note: As an extra advanced exercise, you could try adding a button that when clicked starts a new game by resetting the state of the program and begins it all again.
Hello and welcome to the "Beginners programming" ContentKit. This kit contains resources that you can use the learn and teach general programming principles and the JavaScript language. The material is divided into three sections:
29 |
30 |
31 |
Guides: This section contains a full 8-part tutorial series that you can work through on your own, or use for collaborative learning or teaching a class. This section also contains a number of demos to demonstrate the topics in action.
32 |
Slides: This section contains a slide deck that can be used to give a presentation on the main topic of the TopicKit.
33 |
Slide script: This section contains notes to go along with the slide deck. We have kept these separate from the slides so they are easier to translate.
34 |
35 |
36 |
How to use this ContentKit
37 |
38 |
If you are a self-learning student, you can just open up the Guides and start learning. If you get stuck, try talking to other students, or follow some of the advice in the Getting help section below.
39 |
40 |
If you are a teacher, then a general practice for using the Content Kit is as follows:
41 |
42 |
43 |
Make sure all the students have got a computer available, with a text editor and modern web browser available on them.
44 |
Internet access is very useful, but not essential for this course. You should make sure that you have the complete set of course material available offline, in case Internet access is not availalble. Put it on a USB stick or CD perhaps, so it can be easily shared around all the students before the course starts.
45 |
Get all the students to open up the Guides landing page in their browser, ready to get started.
46 |
You should open up the Guides landing page in your browser too, but in addition have the Slides open in another tab, and also have the Slide script available to refer to in case you need guidance on presenting the slides (ideally have these open on another monitor or computer, or print them out and keep a set beside your computer.)
47 |
Each lesson should take between 1 hour and 1 hour 30 minutes to go through. Take it slowly and give your students regular breaks if going thorugh multiple lessons in one session.
48 |
As well as testing the students with the exercises that you'll find in the Guides, you should feel free to add your own test questions.
49 |
To make finding where you are up and allowing your students to follow along easier, we've included numbers on the left hand side of the Guides that match up to the slide numbers and slide script numbers. Use these to find where you are in relation to the slides if you are following along and get lost.
50 |
51 |
52 |
Getting help
53 |
54 |
When you get stuck with a programming problem and need somewhere to turn for help, life can be frustrating unless you know where to go. If you don't have a programming genius friend you can call, here are some other suggestions:
55 |
56 |
57 |
Search wisely. Professional developers spend a large amount of time searching the Web for answers — you aren't expected to memorise everything! If you don't know how to write a piece of code or you're getting an error, go to your favourite search engine and try
58 |
59 |
Searching for the exact error message you are getting, perhaps along with the API, method, property, etc. you are using.
60 |
Searching for the language you are working in, plus a brief description of what you are trying to do. For example "JavaScript splitting string of text"
61 |
Searching for the name of the library you are trying to use, along with a description of the kind of resource you are looking for, e.g. "Ember.js beginners tutorial"
62 |
63 |
64 |
Ask a question on a forum and see if you can get an answer for it. Stack Overflow is currently the most popular forum type site for programmers. Ask your question on there. Better still, search on there first, as your question may have already been answered.
65 |
Find a local meetup to attend, so you can get to know other people locally who are into the same programming you are doing. It is really helpful to get a network of people around you. Again, search online, for things like "JavaScript Manchester", or "Python Colarado".
66 |
67 |
68 |
Translations
69 |
70 |
No translations as yet. If you are interested in submitting one, please add it to the l10n directory in the repo, and submit a pull request.
71 |
72 |
Contact us
73 |
74 |
These resources are created in collaboration between the Mozilla MDN Technical Writers and Tech Evangelism teams. If you want to reach out to us, get in touch via the #mdn IRC channel and the dev-mdc mailing list.
Table of contents: This is what we will cover in this workshop
48 |
Intro
49 |
Code is just another language: When we want to talk to humans and give them instructions, we use a human language, like English, Chinese or Urdu. When we want to talk to computers and give them instructions, we use code. JavaScript in particular is code that talks to a web browser.
50 |
JavaScript is interpreted: By the JavaScript engine inside the web browser. JavaScript, and other languages like HTML and CSS, are interpreted to output web pages that a computer user can use.
51 |
How the Web works:
52 |
53 |
When a web user types a web address into their address bar or follows a link, their browser requests the web page from the server it is stored on.
54 |
If the request is successful, the server sends the web page files (code, images, etc.) back to the browser
55 |
The browser turns all these files into a web page and shows it to the user.
56 |
57 |
58 |
Server-side vs client-side: Server-side code is run on the server, and the result is then sent to the client and displayed. Think of the code that finds the results when you do an Amazon search. Client-side code on the other hand is sent to the client as is, then interpreted by the client and displayed. We are only covering client-side code in this course.
59 |
HTML: HTML is the language you use to structure your page content and give it meaning. HTML is composed of elements: tags that wrap around content.
60 |
CSS: CSS is the language you use specify what you want your content to look like. It is made up of rules that select element to style, and change their style properties to new values.
61 |
JavaScript: The JavaScript language is comprised of objects that you manipulate to create exciting dynamic functionality on web pages. Programming for the Web.
62 |
Browser developer tools: Every browser has a set of developer tools that can be used to solve problems with web site code (fix bugs). These include a console that can be used to directly test the page's JavaScript. Developer tools are accessed using Ctrl + Shift + I (Cmd + Opt + I on Mac OSX, F12 on Internet Explorer)
63 |
Variables
64 |
Variables: You create a variable using the var keyword, followed by the variable name you choose. You assign a variable using the assignment operator, for example myVariable = "Chris". You can assign the variable different values after it has been created.
65 |
Common variable data types: An integer is a whole number value, and is assigned without quote. A string is a series of characters, and must be surrounded in quotes. A boolean is a true/false value. Arrays and other objects return a data type of object.
66 |
Syntax rules: There are various syntax rules you need to remember about JavaScript. The most important ones are listed here.
67 |
Operators: These slides list the most common JS operators. Most of these are obvious. + is used to add numbers together and join strings together. Modulo returns the remainder after one number is divided by another, and is mainly useful for detecting whether a number is even or odd. For example, 4 % 2 is 0, as 2 divides exactly into 4. 5 % 2 is 1, as 2 divides into 5 twice, with 1 left over.
68 |
Operators: These operators are mostly used to compare values (comparison operators). We've already seen assignment, and we'll see a lot more of the others later in the course. For example, < tests whether one value is less than another — 3 < 5 returns true, because 3 is less than 5.
69 |
Operator precedence is the order in which operators are executed in a sum. Division/multiplication are executed first, then addition/subtraction. This is why 8 + 4 / 3 * 4 perhaps doesn't return the result you thought it might. The divide is run first, then the multiply, then finally the addition. You can force the order using brackets, for example (8 + 4) / (3 * 4)
70 |
Conditions and loops
71 |
Conditional code allows us to test a condition (for example 5 < 3.) If the condition returns true then one block of code will be run. If it returns false, something else will happen. Let's look at the code structure.
72 |
if ... else pseudocode: The basic if ... else code structure looks like this.
73 |
if ... else example: and here is a real code example. Here we prompt the user to enter a town/city name. If they enter "Manchester" then they'll see the first alert message. If they enter anything else, they'll see the second alert.
74 |
if ... else if ... else example: else if() {} is used to chain a further condition check onto the code block.
75 |
logical OR and AND: As you can see in the code examples, these operators can be used to create a conditional check where either or both conditions need to return true before the overall condition will return true.
76 |
Nesting if ... else: This is just fine.
77 |
Loops: These code structures allow you to run the same code several times, updating part of the code each time to iterate through a set of data for example.
78 |
For loop pseudocode: The for loop structure looks like this.
79 |
For loop features
80 |
81 |
i — variable
82 |
starting value — what i begins at
83 |
exit-condition — what value i has to be for the loop to keep running
84 |
iterator — how i changes each time the loop is run
85 |
Run code — the code run each time the loop runs
86 |
87 |
88 |
For loop example: Here is a real for loop example.
89 |
Document Object Model
90 |
The browser converts HTML to a DOM tree: The Document node is the top node in the tree. Then all the elements in your page are converted into nodes, which form a hierarchy based on how they are nested. The html node is top, then the head and body, then the elements inside those.
91 |
JavaScript and CSS accessing the DOM: When you used CSS and JavaScript to affect nodes in the DOM, they walk up and down the tree until they find the element(s) they want.
92 |
Example: JavaScript updating element contents: In this example, we grab a reference to the <h1> element using the document.querySelector() function, then store it in a variable called myH1. We then update the content inside the element by setting a new value for myH1's innerHTML property.
93 |
Canvas
94 |
Canvas is a way to script images using JavaScript. This doesn't sound very impressive to begin with, but you can do a lot with this, such as coding games inside the browser.
95 |
Create a canvas + get a context: To manipulate a canvas, there are three steps to go through:
96 |
97 |
Put a <canvas> element onto your HTML page.
98 |
Grab a reference to that element and store it in a variable.
99 |
Use the getContext() function of the canvas variable to get a 2D drawing context; store this context in a variable. This can then be manipulated to update the <canvas> element.
100 |
101 |
102 |
Draw squares: it is easy to draw squares in canvas — fillRect and strokeRect allow you to draw filled and outline rectangles, respectively. Their four arguments are the x and y coordinates on the canvas, and the x and y dimensions. You cna use fillStyle and strokeStyle to set the colours the rectangles will be, and lineWidth will set the thickness of the stroke.
103 |
Canvas loops: It doesn't take much imagination to start combining loops with drawing on a canvas, to create pretty patterns.
104 |
More loop ideas: Here are some more ideas for you to try in your loops
105 |
More loop ideas: And some more! Bear in mind that there is no easy primitive to draw a circle like there is for a rectangle, so you need to start a drawing path with beginPath(), draw a 360 degree arc(), and then end the drawing path with fill().
106 |
Functions are blocks of code that can be defined once, and then called as many times as you like, meaning much more efficient code. We've already used a number of JavaScript's built-in functions, but here we'll look at how to define our own.
107 |
Sample function: In this sample function, we see one way of defining a function — using the function keyword, followed by the name you want your function to have, followed by brackets(()), followed by curly braces ({}). Inside the curly brances we put our function code. In this case we are generating a random number between 1 and 10, after which we return the result out of the function using the return keyword. This in effect is the result you get returned when you run the function. You have to call (run) the function using its name followed by brackets.
108 |
Function with argument: In this case the code structure is the same, except that inside the brackets we include an argument — this is a variable that we can use inside the function, depending on what result you want. In this case we can now generate a random number between 1 and any number, by specifying it as the argument when we call the function.
109 |
Canvas function: This slide shows a simple example of a function that can generate a canvas sine wave of a certain length, at a certain position on the y axis, as specified by two arguments (separated by commas). A good example of how to encapsulte complex code so you only have to write it once.
110 |
Events
111 |
Events are... a feature of JavaScript that allow us to run code in response to user actions — such as clicking a button or moving the mouse — or actions run by other parts of the code — such as a database successfully being saved.
112 |
Sample event usage (anonymous function): The simplest event example involes a button in your HTML. We grab a reference to this button, then attach an event handler property to it — onclick. Its value is set to an anonymouse function that wil fun when the button is clicked.
113 |
Sample event usage (named function): This example does the same thing, but using a named function (which is the same structure as we saw earlier in the functions section.) This fnuction is rthen called on a separate line, but without the brackets you'd usaually use. This is because including the brackets would run the function straight away, but you don't want it to run until you've clicked the button. This code is more complex, but more reusable. You could potentially call this function multiple times.