This post is part 33 of 33 in the series Programming by Stealth

I had intended to continue running parallel JavaScript and HTML streams for this instalment, but when preparing the notes for the JavaScript stream it became obvious I’d need the dedicate the entire instalment to JavaScript.

What we’ll be doing in this instalment is taking a first look at the concept of software testing. Testing is a vital tool in a software developer’s toolbox. In particular we’ll be looking at two useful concepts, and a tool to help us build and run our test suites. We’ll be looking at the concepts of Test Driven Development (TDD), and Unit Testing (UT). We won’t be religiously adhering to either – instead, I want to encourage you to pick and choose the aspects of these things that work for you.

The tool we’ll be looking at to implement our JavaScript test suites is QUnit. This is a Unit Testing framework developed by the jQuery project, and used by them for jQuery’s test suite.

All code files used in this instalment are contained in a single ZIP file which you can download here.

Read more

Tagged with:

This post is part 32 of 33 in the series Programming by Stealth

In this instalment we’ll continue our twin-track approach of mixing a little JavaScript revision with learning some new HTML. In this case, we’ll revise JavaScript’s error handling mechanism (throw, try & catch), and learn how to use the HTML <select> tag to create dropdown menus and multiple-selection lists.

We won’t be updating our date and time prototypes, but we will be using them in example HTML pages, so in this instalment our two tracks come into direct contact with each other for the first time. We’ll use an HTML page with multiple dropdowns to allow users to select a date, and then render that date in many formats using our pbs.Date prototype. We’ll also use JavaScript’s error handling features to respond appropriately when a user attempts to render an impossible date like the 31st of February 2010.

Finally, the challenge set at the end of this instalment will also combine our prototypes with HTML forms, and JavaScript error handling.

You can download my solution to the challenge set in the previous instalment, and all the code samples for this instalment in a single ZIP file here.

Read more

Tagged with:

This post is part 31 of 33 in the series Programming by Stealth

We’re going to continue our twin-track approach in this instalment – first some JavaScript, then some HTML Forms. We’ll start with my sample solution to the challenge set in the previous instalment, then we’ll look at one final new concept related to JavaScript prototypes – static functions. We’ll wrap up our revision and deeper dive into JavaScript prototypes with a final, finished, version of our algorithm for generating prototypes.

Switching our focus on HTML forms, we’ll look at some important form-specific ARIA roles, we’ll introduce two useful tags for enclosing forms, or parts of forms <fieldset> & <legend>, and we’ll introduce the concept of form data. With those foundations laid, we’ll look at how to add checkboxes and radio buttons to web forms, and how to interact with them through jQuery.

You can download a ZIP file containing the code files for this instalment here.

Read more

Tagged with:

This post is part 30 of 33 in the series Programming by Stealth

In this instalment we’re going to continue with our dual-track approach, first, looking at some more JavaScript prototypes, then switching tack to HTML forms again.

We’ll start with my sample solution to the challenge set in the previous instalment. Then, we’ll move on to add an important enhancement to our prototypes – support for object comparisons. Strictly speaking, this won’t actually be revision – we haven’t looked at the intricacies of comparing objects before.

We’ll finish our JavaScript section with another challenge.

When we switch back to HTML we’ll take a big-picture look at an important accessibility standard named WAI-ARIA. We want to build our forms in a screen-reader-friendly way from day one, and to do that, we need to begin learning about ARIA. ARIA is really quite big, so all we’ll be doing this time is taking in an overview so we understand why it exists, and the basic concepts its built around.

We’ll finish by creating a final, fully accessible, button complete with a pretty scalable icon.

In the next instalment we’ll finally be ready to move on to some more different form inputs, specifically, checkboxes and radio buttons.

Read more

Tagged with:

This post is part 29 of 33 in the series Programming by Stealth

In this instalment we’ll continue with our twin-track approach of revising JavaScript prototypes, and learning about HTML forms.

We’ll start by moving our JavaScript revision out of the PBS playground, and over to NodeJS, getting you much better error reporting. Then we’ll have a look at my sample solution to the challenge from the previous instalment, and we’ll eradicate another bad smell from the prototype. We’ll come face-to-face with the implications of the fact that variables don’t contain objects, but references to objects. If you don’t bear that fact in mind, you can end up with spooky action at a distance that seems like the worst kind of black magic. The kind of bugs that baffle, mystify, and drive you nutty as squirrel poo!

We’ll then switch gears back to HTML forms, where we’ll learn about a very powerful technique for including scalable vector-based icons in your form elements. These very special icons are known as glyph icons, and while rolling your own is a significant undertaking, you don’t have to, because you can use icon sets created by others. We’ll learn about glyph icons using the free and open source glyph icon set from Font Awesome.

You can download a ZIP file containing the sample solution to the previous challenge, and, the example HTML file from today’s examples here.

Read more

Tagged with:

This post is part 28 of 33 in the series Programming by Stealth

In this instalment we’ll continue our parallel streams of JavaScript prototype revision, and web forms.

We’ll start by looking at a sample solution to the challenge set at the end of the previous instalment. We’ll look at what is good about the solution, and where it falls short. We’ll then improve the prototypes through the user of private helper functions.

Before moving on to look at HTML buttons in detail, we’ll learn some new CSS selectors that are particularly useful for styling web forms.

Read more

Tagged with:

This post is part 27 of 33 in the series Programming by Stealth

In this instalment we’ll make a start on a large topic which we have intentionally ignored until now – taking user input on the web. The way this is done is through HTML forms. It will take us a few instalments to learn all about them, so we’ll start with the basics in this instalment.

The code for the examples in this instalment has been collected into a single ZIP file which you can download here.

Read more

Tagged with:

This post is part 26 of 33 in the series Programming by Stealth

After our brief division in the previous instalment, it’s time to get back to learning new things. We’ll learn about data attributes – a mechanism for embedding data into HTML elements.

We’ll also revise what we learned about defining our own object prototypes to start including prototypes in our APIs.

Finally, as a practical worked example, we’ll build a better clock API for Allison’s website. Each Sunday she streams the live recording of her podcast from podfeet.com/live at 5pm at her house. To avoid timezone confusion, Allison would like a clock on that page that shows the current time at her house.

As usual I’ve packaged all the files needed for the worked example into a ZIP file which you can download here.

Read more

Tagged with:

This post is part 25 of 33 in the series Programming by Stealth

This instalment is a little unusual – rather than learning new topics, and then demonstrating them with a few simple examples, we’re going to look at a real-world JavaScript API, see how it works, and in so doing, reinforce what we’ve already learned, and expand our knowledge a little.

The library we’ll be examining is bartificer.linkToolkit.js, a small open source library I released over the weekend. This library bundles some functions for manipulating links in HTML documents. The two main functions of the library are to ensure that links with a target of _blank also specify a rel of noopener (for security reasons), and, to automatically make links leading out of the site open in a new tab, and denoting that fact with an icon appended to the end of the links. You can see the library in use right here on this page!

We’ll be looking at the library from three points of view – the actual JavaScript code, the JSDoc comments, and the documentation produced from those comments, and, project management.

Read more

Tagged with:

This post is part 24 of 33 in the series Programming by Stealth

In this instalment we’ll take our JavaScript skill up a level, learning how to write code that is designed to be re-used by ourselves or by others. When you solve a problem that you know you’ll need to solve again, it’s worth putting in a little extra effort to make your code as easy to re-use as possible. You may decide to share that code with others, or you may not, but either way, it’s in your interest to write it using some simple best practices.

Re-usable code without documentation is all but useless, so, we’ll also learn how to create great API documentation as you code. We’ll learn to do this using the free and open source tool JSDoc.

As a worked example, we’ll re-write our link fixer as an easily re-usable API, and while we’re at it we’ll also add in some extra functionality to make its behaviour more customisable, and hence, more useful to more people.

The sample files used in this instalment, as well as some needed libraries, can be downloaded as a ZIP file here. The examples assume you’ll save the files within the zip in a folder named pbs24 in the document root of your local web server.

Solution to Instalment 23’s Challenge

Before we get stuck into this instalment’s new content, let’s look at a solution to the challenge set at the end of the previous instalment. The challenge was to write a function to find all links in a page, check each to see if it’s internal to the site, or external, and if it’s external, to transform the link to have a target of _blank, a rel of noopener, and to inject an icon after the image to show that it will open in a new window/tab.

Below is my solution. As always, I want to stress that there are an infinity of correct solutions to any programming challenge, so, if your code works, then it’s just as correct as mine!

Writing Re-usable and Sharable Code

Whether you’re writing code for your own re-use in future projects, for sharing with a team, or for publishing to the world, you need to take some extra care to avoid your code having un-intended side-effects. The biggest potential danger is littering of the global scope. The reason you want to avoid using the global scope for everything is that the global scope can only contain one variable with any given name. If you use a globally scoped variable named x in your code, then your code conflicts with every other piece of code that uses a globally scoped variable named x. The fewer globally scoped names your code uses, the less likely it is to conflict with other code.

Many programming languages make use of a concept known as namespacing or packaging, to create a hierarchy of scopes. When you create a new API, you would place all your code in its own namespace, so your code would be completely separated from the global scope. In Java you organise your code into packages, generally named in reverse-DNS style – if I was publishing Java code I could package it as net.bartificer.projectName (Bartificer is my registered business name, and I own the domain bartificer.net). Perl uses a :: separated hierarchy, so the Perl module that drives www.xkpasswd.net is contained within the package Crypt::HSXKPasswd. In both of these examples, there would be/is zero littering of the global scope.

The bad news is that Javascript does not have a built-in mechanism for namespacing. However, a workaround has been developed that uses JavaScript objects, and the concept of function closures to simulate traditional namespaces. It’s not possible to keep the global namespace completely clean using this workaround, but, it does allow us to limit ourselves to a single globally-scoped variable for all our APIs.

Before the workaround can make any sense, I need to explain a few new JavaScript concepts – closures, the ternary operator, and self-executing anonymous functions.

Closures

In JavaScript, when you define a function within another function, the outer function’s scope gets baked into the inner function’s scope permanently, even when the outer function finishes executing. This capture of the external scope is referred to as a closure.

Consider the following code:

We could add this into a page as shown below:

The initialisation function runs exactly once – when the DOM becomes ready. When that function runs, a variable named counter is created, and given the value 0. This variable is created within the scope of the function (initClickCounter()), not within the global scope.

The next thing that happens as the function initClickCounter() executes is that another function is defined, and stored in another locally scoped variable named incrementCounter. We’ll refer to this as the inner function, since it’s defined within another function, specifically, initClickCounter(), which we’ll refer to as the outer function.

The inner function is only defined here, not executed. However, notice that it makes use of the variable counter, which exists in the outer function’s scope. It does not declare this variable (no var in front of it), so it does not have its own copy, it is instead reaching up into its containing scope to access it. It can do this because a copy of the outer function’s scope is permanently added to the inner function using JavaScript’s closure mechanism. The inner function does not get a copy of the variable, it gets a reference to it.

The last thing that happens when the outer function executes is that it adds the inner function to all paragraphs as a click hander.

Once the outer function finishes executing, the inner function has still not been executed even once, it has only been declared, and added as a click handler. Were it not for closures, the variable counter would have vanished into the ether when the outer function finished executing, but it has not – the inner function retains a reference to it.

We can now execute the inner function by clicking on the paragraph in the page. The first time you click, the counter will have a value of 0. It then gets incremented by 1, and alerted. The second time you click, it will be incremented and alerted again. Notice that the count goes up. If we had declared the variable within the inner function that would not happen, it would be a fresh copy each time, but because we are using a variable from the outer function’s scope, it is the same variable each time, so the count keeps incrementing.

Closures can be difficult to understand, as they are a kind of spooky action at a distance (to paraphrase Einstein), but they are absolutely vital to modern JavaScript programming.

Objects as Pseudo-Namespaces (And the Ternary Operator)

If you were to add all your variables, functions, and prototypes directly into the global scope, you would have to chose the names for each one very carefully. If you use a generic name, you are very likely to create an incompatibility with other pieces of code. Rather than trying to pick many unique names, it’s much simpler to pick one name, give it to an object, and add all your functions, variables, and prototypes as key-value pairs within that object.

You’ve already seen this technique in action – the PBS JavaScript playground used a single object named pbs, into which all the available functions were added as key-value pairs, hence you had pbs.say(), pbs.inputs(), and so on. pbs was a variable in the global scope that pointed to an object. That object contained a key named say that referenced a function to render text to the output area, and another key named inputs that referenced a function to read the values from the input text boxes.

This is the approach I recommend you take for all your re-usable code. Choose one name that’s likely to be pretty unique, create a single object with that name, and add all your variables, functions, and prototypes as key-value pairs to that object. I suggest you choose a name that’s likely to be quite unique, and, that references you, or the organisation you work for, in some way.

Remember that there is no reason not to nest these pseudo name-spaces – you could have pbs.util.x, pbs.util.y, as well as pbs.project1.x, and pbs.projec1.y, and so on.

Because my registered business name is Bartificer, I publish all my JavaScript APIs as bartificer.something. For example, I released the API that powers subnetcalc.it as bartificer.ip it contains a number of prototypes for modelling IP addresses and subnets, including bartificer.ip.IP, bartificer.ip.Subnet, and bartificer.ip.Netmask.

If you choose this approach, your code will inevitably be split across multiple .js files, and any one project will only use a sub-set of those files. So how do you declare your object in the first place? You could declare it in a sort of master file that must be included in every project, but that is needlessly cumbersome. A better approach is to declare the object in every file, but only if it does not already exist. This can be done using the following code snippet:

At first glance this is a very odd snippet of code. Your confusion will not be helped by the fact that it makes use of an operator we have not seen before, the so-called ternary operator.

The ternary operator consists of three parts, hence its name:

CONDITION ? VALUE_1 : VALUE_2

If CONDITION evaluates to true, the entire operator will evaluate to VALUE_1, otherwise it will evaluate to VALUE_2.

For example, we could create a variable named x, and set it to the value of another variable named y, if y is positive, or 0 otherwise like so:

You can test this in the JavaScript console. First run the following:

Then run the following:

Now that we understand the ternary operator, let’s look at our sample code again:

The CONDITION is simply pbs, VALUE_1 is also pbs, and VALUE_2 is a new empty object.

So, if pbs evaluates to true, then the entire operator evaluates to pbs, otherwise, it evaluates to a new empty object. The only way an object can evaluate to false is if it’s undefined. So, if the pbs object already exists, nothing changes, the line effectively becomes var pbs = pbs;. However, if the pbs object doesn’t exist yet, the line effectively becomes var pbs = {};, i.e. pbs gets created as a new object containing no keys.

Self-Executing Anonymous Functions

The final strange beast we need to learn about before we can look at the design pattern for simulating namespaces is the so-called self-executing anonymous function. A self-executing anonymous function is a function that is given no name, which gets created and executed in a single step.

In JavaScript, a pair of parentheses can have three different meanings, depending on where they appear in your code. Firstly, when they appear without an name, value, or keyword directly to their left, they simply act to group things together, e.g.:

Secondly, many JavaScript keywords make use of parentheses – e.g. if, while, for, and function.

Finally, if a pair of parentheses containing zero or more coma-separated arguments appears directly after a name or value that is not a keyword, JavaScript will try to execute what ever is to the left of the parenthesis as a function, using the values between the parentheses as arguments to that function, e.g.:

console.log evaluates to a function (console is an object, and log is a key within that object that contains a reference to a function), and by putting the parentheses containing the single argument 'test' directly after it, we call that function with 'test' as the only argument.

We can combine all that knowledge to form the following construction:

The first set of parentheses creates a group that gets evaluated first. That group contains an anonymous function, so the first set of parentheses evaluates to an function. The second set of parentheses appears directly to the right of the first, so they will execute the result of evaluating the contents of the first with 'test' as the only argument. In other words, the anonymous function we just created gets immediately executed. You can try it for yourself in the JavaScript console.

The above construction is hard to read, and would be even harder to read if the anonymous function contained even just a few lines of code, let alone hundreds. Hence, it’s usually written over multiple lines with the following indentation:

A Recipe for Namespacing in JavaScript

We are now ready to look at a very common design pattern for simulating namespaces in JavaScript. I think it’s a good idea to understand what’s happening, but that’s not essential – I think many JavaScript programmers copy-and-paste this design pattern over and over again without fully understanding what’s happening.

To illustrate the technique, let’s create a very simple API that contains just one function – helloWorld(), and present it to the world using pbs as a namespace. The code below should be saved in a stand-alone .js file, say pbs.helloWorld.js (included in this instalment’s ZIP file):

We could now include our simple little API into an existing web page like so:

Having done that, we could call the function like so:

For added context, let’s create a full web page that uses our simple API to generate an alert each time a paragraph is clicked (pbs24b.html in the ZIP file):

Auto-Generating API Documentation with JSDoc

Inspired by JavaDoc, JSDoc is a tool for automatically generating API documentation from JavaScript source files that contain specially formatted comments.

Installing JSDoc

JSDoc is actually written in JavaScript. The easiest way to install it is to use the Node.js JavaScript engine and it’s accompanying package manager, npm. Node is available cross platform, with simple installers for Windows and Mac, and there are packaged versions available for many popular Linux distributions.

Once you’ve installed Node, you should be able to use Node’s package manager to install JSDoc. The basic form of the command will be as follows:

npm install -g jsdoc

The -g means you would like the package installed globally, i.e. system-wide. To install system-wide you need admin privileges, so on Windows you should use a command prompt run as Administrator, and on Linux/macOS you should execute the command with root privileges, either directly, or via sudo. For example, on my Mac I used:

sudo npm install -g jsdoc

You should now be able to create documentation from any javascript file with a command of the form:

jsdoc myFile.js

This will build a documentation website describing myFile.js, and place all the HTML files etc. into a folder named out in the current directory. You can specify as many input files as you like, and JSDoc will build a single unified documentation site describing them all.

We can get more control over the generated document by creating a config file. The config file should be in JSON format, and can be passed to the command with the -c flag. You’ll find a copy of the config I’ll be using in the ZIP file as jsdoc.conf.json:

This very simple config does two things. Firstly, it sets a configuration variable on the default theme that suppresses JSDoc’s default behaviour of adding the code itself into the documentation. I find it just makes the documentation more difficult to read, but if you want to see what it looks like, just change the false to a true. Secondly, it enables JSDoc’s built-in but optional Markdown plugin. When this plugin is enabled, you can use Markdown syntax within JSDoc descriptions.

JSDoc Comments

I mentioned that JSDoc looks for specially formatted comments. JSDoc will try to interpret all comments starting with /** and ending with */. JSDoc is smart enough to ignore leading spaces and *s on multi-line comments. These special comments are referred to as doc comments. You can give a simple description of a function as you create it like so:

This is a very basic example that will result in very basic documentation. JSDoc supports so-called tags that allow you to add more information to your doc comments. These tags all start with the @ symbol. I don’t want to bore you with a definitive list of all available tags, instead, we’ll meet them organically as we go through the series. You can learn more about any tags we do mention, as well as all the other tags that exist, in the JSDoc documentation.

To get started, let’s look at documenting functions. When using an API, a function should be like a black box, what you care about is what goes in, and what comes out. If your function expects arguments, you should specify them in order using the @param tag, one tag per argument, and each tag starting on a new line. Each @param tag should take the following form:

@param {TYPE} ARGUMENT_NAME - DESCRIPTION

The TYPE should be a valid native JavaScrip type, like string, number or boolean, the name of a prototype, like Object, or, a reference to a custom type of your own creation (more on that later in the series). The ARGUMENT_NAME is just the name of the argument, and the description should be some text describing the argument. The type and description are optional, and if you don’t want to set a description, also leave out the dash preceding it. Oh – also, if there is a description, the dash should have exactly one space before it and one space after it.

To specify what a function returns, use the @returns tag:

@returns {TYPE} DESCRIPTION

You can leave out either the type or the description if you like (but not both).

Given what we know now, let’s re-write our sample function:

Note that we are using Markdown syntax to mark some items for rendering as code snippets, specifically, we are using the back-tick to do that.

Something else functions can do is throw exceptions. You can document this using the @throws tag. This tag takes the following form:

@throws {EXCEPTION_PROTOTYPE} DESRIPTION

Where EXCEPTION_PROTOTYPE is the prototype of the exception that could be thrown. If your function can throw multiple types of error, you should add multiple @throws tags to the doc comment.

We could re-write our function so it throws an exception on invalid arguments as follows:

Finally, before we move on from functions, I also want to mention the @example tag, which you can use to add sample code into your documentation. This tag works over multiple lines – everything until the next tag, or, until the end of the comment is considered part of the example. Let’s re-write our function one last time:

As a proper worked example, let’s create documentation for our simplistic pbs.helloWorld API.

The first thing we should do is add a doc comment to the very top of the file. This will form the homepage of the documentation. To do that, we’ll use two tags – @overview, and @author.

Because we use namespaces, we need to tell JSDoc that it should consider pbs a namespace. We do that by adding a doc comment directly above our declaration of the pbs variable, and ending that comment with the special tag @namespace.

Finally, we should add a doc comment to the helloWorld function. Because this function expects no arguments, returns no value, and throws no exceptions, the @param, @returns, and @throws tags are intentionally omitted.

This is how our file now looks:

You may notice that the overview contains a JSDoc tag that I have not mentioned yet, {@link pbs}. This in-line JSDoc tag can be used in any JSDoc description to insert a reference to a documented item. In this case, a link to the documentation about the pbs namespace.

We are now ready to generate our documentation. Start by opening a command prompt in the same folder as the pbs.helloWorld.js and jsdoc.conf.json files. From there, run the following command:

jsdoc pbs.helloWorld.js --destination docs-helloWorld -c jsdoc.conf.json

Assuming you extracted the contents of the ZIP file into a folder named pbs24 in the document root of your local web server, and, that your local web server is running, you should now be able to access the documentation you’ve just created at the URL http://localhost/pbs24/docs-helloWorld/.

A Challenge

The challenge this time is to create a first-pass at an API for rendering a clock showing the current time in any given timezone. Before we’re ready to do that, we need to look at a JavaScript API for converting between timezones.

A Quick Introduction to Moment.js

At the moment, the most powerful looking open source JavaScript library for manipulating dates is Moment.js, and it has an extension specifically for manipulating timezones. The two JavaScript files needed to use Moment.js‘s timezone features are included in the contrib folder within the zip file.

As we did with with URI.js, this is merely a sampler of what Moment.js can do, focusing on the features we need to achieve our goal. This is not a tutorial on Moment.js. You can find the full documentation at momentjs.com/docs.

We can create a moment object representing the current time in a given timezone as follows:

The timezone string should be a TZ string as defined in the IANA time zone database. Thankfully Wikipedia publishes a full listing of the database – the value we need is in the third column.

We can then access one or more aspects of the time as a string using the .format() function. For example, to see the hours and minutes separated by a colon we could use:

You can get a full listing of all the formatting characters here, but for our assignment we only need to know the following:

A Starting Point

Rather than starting with a blank canvas, start with the following two files (pbs24-assignment.html and pbs.renderClock.js in the ZIP file):

You don’t need to make any changes to this file. You can use it as-is to test that your clock function is working. This file must be located in the same folder as the contrib folder, and the pbs.renderClock.js file in order to function.

The JSDoc comment describing what the function should do is already in place, as is the start and end of the function.

The Assignment

You simply need to add the functionality into the pbs.renderClock() function in pbs.renderClock.js to make it actually do something.

How you make the function do its thing is entirely up to you, but I suggest the following basic design:

  • First, empty the span – to be sure you are working on an empty canvas, so to speak.
  • Create three spans, one for the hours, one for the minutes, and one for a separator character, and save them into three variables in pbs.renderClock()‘s scope, and then inject them into the span.
  • Create an inner function within pbs.renderClock() and give it a name. This function should get the current time, and reaching out into pbs.renderClock()‘s scope, use the variables there to update the hours and minutes to their currently correct value.
  • Create an interval that runs every 60 seconds and calls your inner function.
  • For bonus credit, can you make the separator blink? You might find jQuery’s .fadeTo() function useful.

Conclusions

We’ve learned how to use the magic of closures to package our code into re-usable libraries, and, we’ve learned how to use JSDoc to generate documentation for our library’s APIs. So far our APIs have been very simplistic – so simplistic some people might even argue that they don’t deserve to be called APIs at all! That will change in the next instalment, when we’ll create a powerful API for adding arbitrarily many clocks, each in any timezone, to a page in a configurable way. To do that we’ll need to learn another new concept – data attributes – a way of embedding data into an HTML element.

Tagged with:

keep looking »