16Introducing JavaScript and jQuery


Files to hold the JavaScript code

All the JavaScript and jQuery code that we write will be stored in separate files, in just the same way that the CSS is stored in separate files.

Each web page will need two JavaScript files, a common JavaScript file that is loaded by the web page to handle the sticky navigation (this is the same for every page, just like style.css) and a page specific JavaScript file that handles all the slow scrolling on the web page. The files are named as follows

  • script.js

Common file to handle the sticky navigation
  • cc-ss-scroll.js

Page specific file to handle slow scrolling

The files are stored as follows in the directory structure:

Figure 16.18 - Storage locations for JavaScript files
Figure 16.18   jStorage locations for JavaScript files

JavaScript files always have the extension .js (again this is not an absolute requirement, but do it anyway, Brackets expects JavaScript files to have the .js extension and it is common practice everywhere).

If you’re starting from scratch with these files, create the folder structure for your page within the 01-pages directory (as shown in Figure 16.18 above) and within the 05-js folder create an new file in Brackets and rename it cc-ss-scroll.js where cc is the chapter number and ss is the section number (these should match the start of the HTML filename). For the rest of this section I’m using the 99-00-typicals.html file and the 01-pages directory has this in it:

Figure 16.19 - 99-00-typicals folder structure
Figure 16.19   99-00-typicals folder structure

Next create the script.js file in the 11-resources/05-js directory.

  • I’m going to assume that these files are empty and build up the code from scratch, if you have downloaded the completed file from the website template, the .js files will already be complete, you can either just delete the stuff that’s in there if you want to build it yourself or just accept what’s there and compare it with what I’m doing here.


Creating the basic file

There is a standard format for the contents of a JavaScript file, the basic container for all the JavaScript and jQuery code, looks like this:

the basic JavaScript file container
$(document).ready(function() {                  /* START OF PAGE READY FUNCTION */

/* ****************************************************************************
   **************************************************************************** */

});                                             /* END OF PAGE READY FUNCTION */
Code 16.3   The basic JavaScript file

JavaScript really likes brackets, braces and semicolons, they’re everywhere and, best of all, if you miss one, it screws everything up.

Author’s note

I’m not entirely sure that I like JavaScript; I can see that it is very powerful and lets you do pretty much anything you want on a web site. It looks awful though and trying to read and understand it is virtually impossible.

It is hard to get a grip of JavaScript, it’s slightly easier when using the jQuery aspects, but even then it is not very intuitive. I struggle with it and I’ve been coding with C and machine code since I was at school (on an old Sharp MZ80A, my second computer — my first was a ZX81).

I think JavaScript is a language that you have to use a lot before it clicks, I tend to just use it when I need to and it is almost a re-learning exercise every time.

Mostly I just hate all those fucking brackets, braces and semicolons.

Let me take you through the bit of meaningless (but nonetheless, essential) drivel we’ve just written.

I could compress the whole thing into a single line, and that is kind of what it is, it is a single instruction that will contain all our code:

$(document).ready(function() {  /* YOUR CODE */  });

This is jQuery at its most fundamental, wherever you see the dollar sign ($), you know you are dealing with jQuery.

  • The dollar sign only has a special meaning once the jQuery library has been loaded, it does not mean anything in JavaScript itself (it could be assigned to a variable just like any letter, e.g. var $=500; has the same usage as var A=500;).

The general syntax for jQuery syntax is (I’ve coloured the brackets to show the paring):



  • $

Indicates this is accessing some method within the jQuery library
  • (selector)

Is used to identify some HTML component or element
  • action()

Whatever is in the brackets gets executed when the action is detected, some actions are event driven e.g. click, some happen no matter what (they always execute)

You can see that what we have at the start of the file fits this kind of syntax (I’ve coloured the brackets to match the colours in the syntax above:

$(document).ready(function() { /* YOUR CODE */ });

So, what are we doing?

The simple answer is that we are waiting for the HTML page and all its associated files to load (be ready in jQuery terminology) before we execute any of our JavaScript code.

That’s all it does, it waits for the web page to load completely and then executes any code we put in between the braces (or squiggly brackets as everyone calls them).

If you are happy with that explanation, skip the next bit, it is detailed and at the end of it, it will just confirm what I said above.


Understanding $(document).ready(function());

The code $(document).ready(function() { }); is the jQuery way of waiting for the page to load before we do anything (execute any code).

This is good practice, our JavaScript files are all loaded in the <head> section of the HTML, if the code started executing straight away, the rest of the page wouldn’t have been rendered in the browser (yet) and the code would fail.

Let’s say we were using the code to manipulate the appearance of a table, the code would have loaded before the table was loaded into the browser and it would fail because it couldn’t find the specified table (the table wouldn’t be in the browser yet).

In its simplest form, the code is this:


In the jQuery context (document)is a selector where document†1 is the thing that loaded our .js file, in this case it is the 99-00-typicals.html file.

With web pages that run jQuery, it is a fair assumption that document means the HTML file of the web page.

†1 The document is often called the DOM in jQuery terminology. DOM stands for Document Object Model; it means the HTML page that ran the JavaScript code. I think it is called an object model because it turns the page into a series of objects, these being the elements, classes and IDs that have been defined for the page. It identifies them as specific objects so that we can do things to them (e.g. hide or display them, change their properties &c.).

The action in this case is ready(). This is a jQuery method; you can see its formal description here. The ready method executes any function that is contained within its brackets when the document (in this case) has fully loaded.

  • It is the browser itself that knows when the page has loaded; the ready method just interrogates the browser to find out if this has happened

In this case, the ready method is going to execute the function:

function() { }

The word function is a JavaScript keyword; it defines what follows as a function (a module or section of code that does something.

The formal syntax for a function is:

function functionName (parameters) {code}

The function we are using is a bit of a cut down version of the full thing, its missing the parameters, it’s also missing a name and for the moment it is missing any code as well.

Parameters are things that are passed into functions from outside, if we had a function that converted Fahrenheit to Celsius, it would have a parameter called Fahrenheit that passed the Fahrenheit value into the function.

It is not necessary for functions to have parameters and in our case, the function will have a series of operations within it, all of which will use elements of the document and these do not need to be passed as parameters (they are accessible via jQuery methods). Hence our function has empty brackets ().

  • For those familiar with C, the function() here is comparable to the main() function in C. It holds the executable code.

The absence of a function name is perhaps more unusual, generally functions are given names; it would be very confusing trying to call them if they didn’t have a name.

In JavaScript, functions without a name are called anonymous functions and they are generally assigned at runtime.

In our case, we are defining a single function that holds all our code, it is created when the browser executes the code (it is essentially just acting as a container for whatever we write), and will run until it is finished (i.e. when the page closes).

Anonymous functions are not called by other functions, they are created at runtime and execute until they finish what they are doing, they cannot be called repeatedly (like a named function acting as a subroutine), if it’s needed again, it must be recreated as part of the code).

  • It is perfectly acceptable to give the function a name,
    $(document).ready(function MGfunc() {});
    works just as well as:
    $(document).ready(function() { });

The final form of the code:

$(document).ready(function() {                  /* START OF PAGE READY FUNCTION */

/* ****************************************************************************
   **************************************************************************** */

});                                             /* END OF PAGE READY FUNCTION */

is the standard form to use and it is used absolutely everywhere on the internet.

It is just a placeholder to put your code and it waits until the web page is fully loaded before running your code.

Put this code in both the cc-ss-scroll.js and the script.js files, they should be identical at this stage.

End flourish image