Remember that you can download a zip file, to get our standard template.
Here's the JS from the template:
The <script>
tag (lines 1 and 12) embeds JS within HTML. use strict
makes JS detect possible errors for us. For example, if we forget to declare variables, JS will complain. It's like Option Explicit
in VBA.
Collisions are bad
The third line is:
var BeingHuman = BeingHuman || {};
We're using this to make a namespace.
Huh?
Here's the sitch. There's a bazillion useful JS libraries, for mapping, audio, animation, you name it.
Say you want to add a mapping library called Mapotron to your app, and an animation library called Anitron. (I made up those names.) You look in their docs, and they tell you to include the libraries in your code like this:
<script src="https://cdn.thing1.com/mapotron.js"></script>
<script src="https://cdn.thing2.com/anitron.js"></script>
Let's say the file mapotron.js
starts like this:
var timerDelay = 6000;
The file anitron.js
starts like this:
var timerDelay = 60;
They both declare a variable called timerDelay
. Argh! The programs collide.
Once collision can lead to an epic fail.
Namespaces to the rescue
Now, suppose the libraries Mapotron and Anitron had namespaces. mapotron.js
starts like this:
var Mapotron = Mapotron || {};
Mapotron.timerDelay = 6000;
anitron.js
starts like this:
var Anitron = Anitron || {};
Anitron.timerDelay = 6000;
Mapotron
and Anitron
are different namespaces. The variables are declared inside the namespaces, so the variables don't collide. (How this works doesn't matter for now.)
You should make a namespace for every project. Just pick a name, and use it. Like:
var AngryPixels = AngryPixels || {};
Or:
var LoftyMelons = LoftyMelons || {};
Or:
var UglyPositrons = UglyPositrons || {};
Or:
var CheckeredZebras = CheckeredZebras || {};
jQuery
Here's the template again:
Let's talk about these lines:
(function($) {
...
}(jQuery));
See jQuery
in the last line? jQuery is a library that makes JS programming easier. jQuery is included in the template:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"...
jQuery uses the $()
function to do most of its work. This code…
(function($) {
...
}(jQuery));
… makes sure that you can write your code with the $()
function, and be sure that you're calling jQuery. How does it work? Doesn't matter.
The namespace idea is an example of a pattern. A pattern is a common way of doing things, that works. If you forget how to do things for your own project, check the pattern catalog. You can find the patterns you need, and copy-and-paste their code.
The jQuery ready() event
Here's the template again:
Let's talk about:
$(document).ready(function () {
...
});
ready()
is an event, that is, something that happens. ready()
is triggered when the page is loaded and ready to go, but before the user gets to do anything. ready()
is where you put code that initializes the page.
Remember that we tool the navbar HTML out of each page, and put in a separate file, called navbar.html
. When the browser loads a page, there is no navbar HTML on the page, only a place for the navbar to go:
<div id="navbar"></div>
We load the navbar HTML into the <div>
. This code from the template will do it:
$("#navbar").load("library/includes/navbar.html");
It says, "OK, jQuery, find something on the page with an id
of navbar
. Then load into it the contents of the file at library/includes/navbar.html
.
For example, if navbar.html
has this in it…
<p>Rosie is a good dog!</p>
… then the line…
$("#navbar").load("library/includes/navbar.html");
… would turn…
<div id="navbar"></div>
… into…
<div id="navbar"><p>Rosie is a good dog!</p></div>
OK, we want to inject the navbar as the page is loaded. That's what the ready()
event is for.
Here's the code again:
$(document).ready(function () {
//Load the navbar from the library.
$("#navbar").load("library/includes/navbar.html");
//Load the footer from the library.
$("#footer").load("library/includes/footer.html");
});
So, the first thing that happens once the page is loaded, is that navbar.html
and footer.html
are injected into the page.
Event-driven programming
Perhaps you're written programs where all of the code is in one block. It starts at the top, runs until it reaches the bottom, and the program is done. Data analysis programs in Python or VBA are often like this.
Most JS programming is different. It's event-driven programming. It breaks programs up into fragments. Each piece is attached to an event, like loading a page, or clicking a button. The code pieces fit together to make an entire app.
Watching it happen
This is very important. Follow along, with your own page. If you don't do it, your course warranty will be void. (OK, there is no warranty, but you should follow along on your own computer.)
Copy the standard template, unzip it. Edit index.html
. Put in some HTML, whatever you want, maybe a list of interesting manhole covers.
Make a directory in your littlejs
subdomain. Upload all of the files there.
Open the page in a browser.
Open the developer tools. F12, remember.
These are Firefox's developer tools. Chrome, Edge… they're all similar.
You've seen the Elements tab before. It helps you explore the HTML, and the styles for each element.
Click on the Debugger tab, called Sources in Chrome. This lets you explore the JS on the page.
Click on the name of your file in the left pane, and its code will show on the right. Scroll down to the ready()
function, and click on the line number of the line that loads navbar.html
:
This sets a breakpoint. When running code, the browser will stop on the line you chose. It will stop before running the line, so you can see what the line does.
Reload the page (F5, or Ctrl+R). This is what you'll see:
You can see what the page looks like in the top pane. You can see some content, but there is no navbar or footer.
That makes sense. The code that loads them hasn't run yet.
Run the current line, by pressing F10. The navbar appears. It appears right away in Firefox, not until later in Chrome.
Press F10 again to run the next line. The footer appears.
Press F8 to let the script finish.
Let's mess it up
Let's see what happens when there's a JS error. Add an invalid line to your JS. Here's what I did:
Remove the breakpoint, close the developer tools (F12), and reload the page.
Here's what I saw:
No navbar or footer. But no error messages, either. Just looking at the page, I wouldn't know anything was wrong, unless I knew what I should have been seeing.
This is an issue with JS: it fails silently. Unless you know where to look for errors.
Open the dev tools, and click on the Console tab. The console is where JS logs errors, among other things.
When you're developing an app, leave the console open. This is how you will know whether there were errors. Sometimes things will go wrong, and you won't even notice the effect on the page until later. Leaving the console open will help.
Programming is frustrating
Expect your programs to fail. That's normal. I've been programming for decades, and I still expect my programs to fail the first time through, no matter how simple they are.
How to make programming less frustrating?
- Know what to do when things go wrong.
The dev tools, and especially the debugger, are key. As we go, you'll learn how to use the debugger to find errors.
A final point. You can't predict how much time you'll need to fix bugs. Start projects early, so you have time to hunt bugs. Your life will be easier.
Exercise
library
directory, and anything else you need.
Make the page show a popup message when it loads: "This page by YOUR NAME."
Hint: try the JS alert()
function.
Put the page somewhere in your littlejs
subdomain. Submit the URL.
(If you were logged in as a student, you could submit an exercise solution, and get some feedback.)
CoolThing
Summary
- Our template contains JS.
- It defines a namespace. Choose your own, like
BeneathCrows
, orSumoSummary
. - Put your initialization code in the
ready()
event's function. - The dev tools and the debugger will save your sanity.
- Don't leave projects until the last minute.