You are on page 1of 42

Making Stuff Happen

There’s a few ways to try out JavaScript, and when learning it’s
best to try them out to see what works for you. But first, how
does JavaScript relate to HTML and CSS?
HTML, CSS and JavaScript
Mostly, JavaScript runs in your web browser alongside HTML and CSS, and can be added to any
web page using a script tag. The script element can either contain JavaScript directly (internal) or
link to an external resource via a src attribute (external).
A browser then runs JavaScript line-by-line, starting at the top of the file or script element and
finishing at the bottom (unless you tell it to go elsewhere).

Internal
You can just put the JavaScript inside a script element:

<script>
alert("Hello, world.");
</script>

Link To Us!If you've found HTML Dog useful, please consider linking to us.

External
An external JavaScript resource is a text file with a .js extension, just like an external CSS
resource with a .css extension.
To add a JavaScript file to your page, you just need to use a script tag with a src attribute
pointing to the file. So, if your file was called script.js and sat in the same directory as your
HTML file, your script element would look like this:

<script src="script.js"></script>
You might also come across another way on your view-source travels: inline. This involves
event attributes inside HTML tags that look something like <a href="somewhere.html"
onclick="alert('Noooooo!');">Click me</a> . Just move along and pretend you haven’t witnessed this
aberration. We really, really, really want to separate our technologies so it’s preferable to avoid
this approach.
Console
The last way is great for getting instant feedback, and it’s recommend if you just want to try a
line out quickly.
In a modern browser you’ll find some developer tools - often you can right click on a page, then
click “inspect element” to bring them up. Find the console and you’ll be able to type JavaScript,
hit enter and have it run immediately.
Search the net if you can’t find your dev tools or console - they’re changing in browsers all the
time.

Let’s go!
To get started, the best way is the internal method. You can modify the contents of
the script element and refresh the page just like you’re used to - quick and easy.
Now it’s time to learn some JavaScript. Good luck!

Variables and Data


Storing data so we can use it later is one of the most important
things when writing code. Fortunately, JavaScript can do this! If
it couldn’t, it’d be pretty darn useless.
So let’s ask the user (that’s you) for their surname (check your driving license, or ask a friend).
By the way, this assumes you’ve jumped into a browser and are typing into your console.

var surname = prompt('Greetings friend, may I enquire as to your surname?');


A little box will pop-up, asking (very courteously if I may say) for your surname. Type your
surname in and hit ‘OK’.
The surname you entered is now saved, and it can be referred to as surname. You can get what
you entered back out again by typing surname into the console. You should see your surname
appearing back to you underneath! Exciting!
You’ve created a variable.

Variables
Think, if you will, of a variable as a shelf with a name so it’s easy to get back to. You’ve named
a shelf surname.
You can name a variable anything you like, but it’s best to name it in a way that tells what
you’ve stored there. For example, surname is better than mything or s.
When you type a variable name into the console you are asking the browser, which looks after
the shelves, to go find the shelf and give what’s on it to you. This is also known as the
variable’s value. The value can be almost anything - in surname, you’ve stored some letters,
known as a string. You can also store numbers and a myriad other kinds of data.
So, a variable has a name and a value.
They are the way we store data, and you’ll be using them a lot.
There are two parts to creating a variable; declaration and initialization. Once it’s created, you
can assign (or set) its value.

Declaration
Declaration is declaring a variable to exist. To return to the shelf metaphor, it’s like picking an
empty shelf in a massive warehouse and putting a name on it.
As above, to declare a variable, use the var keyword followed by the variable name, like this:

var surname;
var age;
Notice those semicolons (“;”)? Almost every line in JavaScript ends in a semicolon - you’ll be
using them a lot.

Initialization
Initialization is giving a variable its value for the first time. The value can change later, but it is
only initialized once.
You initialize a variable using the equals sign (=). You can read it as “the value of the variable
on the left should be the data on the right”:

var name = "Tom";


“Tom” is a string - a collection of letters. A string is surrounded by single or double quote
marks.

var age = 20;


20 is just a number - and numbers don’t go in quotes.

Assignment
As mentioned, you can set a variable’s value as many times as you like. It’s
called assignment and it looks very similar to initialization. You again use the equals sign, but
there’s no need for the var keyword because we’ve already declared the variable.
It’s like this, yo:
name = "Andy";
age = 43;
Only do this if you’ve declared the variable using the var keyword!

Doing Math
Variables can be used to store strings and numbers (amongst
other things), but here the focus is on numbers.
How much fruit?
In your console, let’s create two variables. One will be the number of apples we have, the second
will be the number of pears.

var apples = 5, pears = 10;


That creates two variables… but there’s only one var keyword? Yup, it’s a shorthand for
declaring and initializing multiple variables at the same time. By using the var keyword once and
separating the new variables with commas you can save yourself some work.
Now, use these two variables to figure out how many pieces of fruit there are in total.

var piecesOfFruit = apples + pears;


So that’s new.
You’re asking the browser to work out the sum on the right before assigning the result
to piecesOfFruit - and you’re not adding the variable names, you’re adding the values of the
variables. The browser knows that, when it sees a variable like this, you want to do something
with the value. So it goes and gets each variable’s value before doing the sum.
The sum is called piecesOfFruit, not pieces of fruit. This is because variable names cannot
contain spaces! There’s a set of rules somewhere about what you can and can’t use, but for now
just use letters with no spaces.
You may have also noticed that the uppercase “O” on “Of” and “F” on “Fruit”. This is a
convention, called camel casing (cos of the humps), that makes the variable name easier to read.
You can call a variable anything you want, but pIeCEsOFfRuiT is pretty hard to read, no?
Here’s a tip for you: code is read many, many more times that it is written. So it’s really, really
important to make sure your code is easy to read. Really important.

Splitting the fruit


Let’s say you want to split your fruit between 3 people. How much fruit does each person get?

var piecesForEachPerson = piecesOfFruit / 3;


Thank goodness we have this JavaScript thing, otherwise you’d need a calculator for that one…
You’re using a forward slash (“ / ”) to indicate division: divide the thing on the left by the thing
on the right.

Precedence & operators


For doing sums you can use various symbols: add (“ + ”), subtract (“ - ”), divide (“ / ”) and
multiply (“ * ”).
Mathematical symbols are called operators; that is, they operate on some data. We’ll meet even
more operators later on, but you should know that, like on a calculator, the symbols are worked
out in a particular order, called operator precedence. Things in parentheses - that’s these: “ ( ”
and “ ) ” - are done first, then multiplication and division, then addition and subtraction.
Here’s an example, stepping through how the browser runs it:

(10 + 2) / 2 + 4 * 2
The part in brackets is worked out first. So this becomes…

12 / 2 + 4 * 2
…which works out to…

6+4*2
Then things are done in operator precedence order. If multiple sums are of the same precedence
then they are evaluated left to right.
The multiplication is higher precedence so is done first, which works out to…

6+8
This is used to work out the final value:

14
Whew!

Logic
A really important part of programming is being able to compare
values in order to make decisions in code. When a comparison is
made the outcome is either true or false; a special kind a of data
called a boolean. This is logic.
Like when doing math, there’s a set of operators that work on booleans. They are used to
compare two values, on the left and right of the operator, to produce a boolean value.
The following comparisons are made in the console. The result we get from each line (shown
underneath) will be true or false; these are booleans.

Equality
To find out when two values are equal, use the triple equals operator (“===”).

15.234 === 15.234

true

We can also determine if two values are not equal using the triple not equal operator (“!==”).

15.234 !== 18.4545

true

It’s important to know that strings containing a number and an actual number are not equal.

'10' === 10

false

Advertise Here!On a long-established, well-read, well-respected web development resource.

Greater than and less than


Comparing two numbers is useful, for example, to determine which of two is larger or smaller.
This first example is a comparison of 10 and 5 to see if 10 is larger, using the greater
than operator (“>”).

10 > 5

true

Next we use the less than operator (“<”) to determine if the left value is smaller.

20.4 < 20.2

false

That example gives back (or returns) false, because 20.4 is not a smaller number than 20.2.
Combined comparisons
Combining a comparison of equality and size can be done with the greater than or equal
to and less than or equal to operators (“>=” and “<=” respectively).

10 >= 10

true

10 <= 5

false

Conditional
Logic is used to make decisions in code; choosing to run one
piece of code or another depending on the comparisons made.
This requires use of something called a conditional. There are a
few different conditionals that you might want to use, but we’ll
just focus the one used most commonly: if.
If
It’s very simple: if some logic (the condition) is true, run a block of code. You can also supply
more code to be run if the condition is not true, and supply additional conditions and blocks of
code to optionally be run. These forms are called if-else, as you’ll see below.
The most simple if statement looks something like this:

if (10 > 5) {
// Run the code in here
}
The code between the braces - “{” and “}” - is called a block, and this one is linked to
the if statement. It’s only run if the conditional (between the parentheses) is true.
10 is indeed greater than 5, so the code in the block would run.
Oh, and the line starting “//”? The double slashes indicate comment, which means that
everything after the slashes until the end of the line is ignored by the browser.
If-else
The if-else form of an if statement is used to run an alternative piece of code if the conditional is
not true. The code in the if block below will be ignored, for example - only the code in
the else block will be run.

if (43 < 2) {
// Run the code in here
} else {
// Run a different bit of code
}

Looping
Loops are a way of repeating the same block of code over and
over. They’re incredibly useful, and are used, for example, to
carry out an action on every item in an array (we will come to
arrays later) or in searching.
Two of the most common loops are while loops and for loops. They combine a conditional and a
block, running the block over and over until the logic of the conditional is no longer true, or until
you force them to stop.

While
A while loop repeats a block of code while a condition is true. Like an if statement, the condition
is found in parentheses.

var i = 1;
while (i < 10) {
alert(i);
i = i + 1;
}
// i is now 10
After looping has finished the code carries on running from just after the closing brace (“}”) of
the loop’s block.

For
A for loop is similar to an if statement, but it combines three semicolon-separated pieces
information between the parentheses: initialization, condition and a final expression.
The initialization part is for creating a variable to let you track how far through the loop you are
- like i in the while example; the condition is where the looping logic goes - the same as
the condition in the while example; and the final expression is run at the end of every loop.

for (var i = 1; i < 10; i++) {


alert(i);
}
This gives us alert boxes containing the numbers 1 to 10 in order.
By the way, i++ is equivalent to i = i + 1.

Functions
Functions are reusable blocks of code that carry out a specific
task. To execute the code in a function you call it. A function
can be passed arguments to use, and a function may return a
value to whatever called it.
You can save functions as the value of a variable, and you call a function using this variable and
a pair of parentheses. This is also called invoking the function.

doSomething();
findAnInterestingThing();
To create a function, use the function keyword. You then list the arguments in parentheses, and
then supply a block that contains the function’s code. Here’s a function that adds two numbers:

var add = function (a, b) {


return a + b;
};
a and b are the function’s parameters, and the value it returns is signified by the return keyword.
The return keyword also stops execution of the code in the function; nothing after it will be run.

var result = add(1, 2); // result is now 3


This calls add with the arguments 1 and 2, which, inside add, will be saved in the
variables a and b.
Objects
JavaScript objects are like a real life objects; they have
properties and abilities. A JavaScript object is, in that sense, a
collection of named properties and methods - a function. An
object can be stored in a variable, and the properties and
methods accessed using the dot syntax.
A human, for example, has a name and an age, and could talk, move or learn JavaScript. Name
and age are properties of the human, and are essentially pieces of data. Talking, moving and
learning are more like functions - there’s some complex behavior involved. When a JavaScript
object has such an ability, it is called a method.
Variables can hold objects, and creating an object is done using a special syntax signified by
braces:

var jedi = {
name: "Yoda",
age: 899,
talk: function () { alert("another... Sky... walk..."); }
};
The Jedi’s name and age are properties - they are essentially variables within the object and can
store anything a variable can. talk is a property that holds a function - a method.
You can get data back out of an object using the dot syntax:

jedi.name;

Yoda

jedi.age;

899

jedi.talk();

//produces an alert box

You can also reassign properties of an object:


jedi.name = "Mace Windu";
And add new ones on the fly:

jedi.lightsaber = "purple";
Properties can be any kind of data including objects and arrays. Adding an object as a property of
another object creates a nested object:

var person = {
age: 122
};

person.name = {
first: "Jeanne",
last: "Calment"
};
Creating an empty object and adding properties and methods to it is possible too:

var dog = {};

dog.bark = function () { alert("Woof!"); };

Arrays
Arrays are lists of any kind of data, including other arrays. Each
item in the array has an index — a number — which can be
used to retrieve an element from the array.
The indices start at 0; that is, the first element in the array has the index 0, and subsequent
elements have incrementally increasing indices, so the last element in the array has an index one
less than the length of the array.
In JavaScript, you create an array using the array-literal syntax:

var emptyArray = [];

var shoppingList = ['Milk', 'Bread', 'Beans'];


You retrieve a specific element from an array using square bracket syntax:
shoppingList[0];

Milk

It’s also possible to set the value at a particular index, again using the square bracket syntax:

shoppingList[1] = 'Cookies';

// shoppingList is now ['Milk', 'Cookies', 'Beans']

You can find the number of elements in the array using its length property:

shoppingList.length;

You can use push and pop methods to add and remove elements from the end of the array:

shoppingList.push('A new car');

// shoppingList is now ['Milk', 'Bread', 'Beans', 'A new car']

shoppingList.pop();

// shoppingList is back to ['Milk', 'Bread', 'Beans']

Here’s an example that creates, pushes, pops and iterates over an array, passing each name to a
function called helloFrom. helloFrom returns a string with a greeting: “Hello from ” and then the
person’s name. After the pushing and popping, the final list of people is: “Tom”, “Yoda”, “Ron”
and “Bob”.

var helloFrom = function (personName) {


return "Hello from " + personName;
}

var people = ['Tom', 'Yoda', 'Ron'];

people.push('Bob');
people.push('Dr Evil');
people.pop();

for (var i=0; i < people.length; i++) {


var greeting = helloFrom(people[i]);
alert(greeting);
}
The DOM
The Document Object Model is a way to manipulate the
structure and style of an HTML page. It represents the internals
of the page as the browser sees it, and allows the developer to
alter it with JavaScript.
If you’d like to have a look at the DOM for a page, open up the developer tools in your browser
and look for the “elements” pane. It’s a great insight into how the browser thinks, and in most
browsers you can remove and modify elements directly. Give it a try!

Trees and Branches


HTML is an XML-like structure in that the elements form a structure of parents’ nodes with
children, like the branches of a tree. There is one root element (html) with branches
like head and body, each with their own branches. For this reason, the DOM is also called
the DOM tree.
Modifying the DOM, by picking an element and changing something about it, is something done
often in JavaScript. To access the DOM from JavaScript, the document object is used. It’s
provided by the browser and allows code on the page to interact with the content.

Getting an Element
The first thing to know is how to get an element. There are a number of ways of doing it, and
browsers support different ones. Starting with the best supported we’ll move through to the
latest, and most useful, versions.

By ID
document.getElementById is a method for getting hold of an element - unsurprisingly - by its ID.

var pageHeader = document.getElementById('page-header');


The pageHeader element can then be manipulated - its size and color can be changed, and other
code can be declared to handle the element being clicked on or hovered over. It’s supported in
pretty much all the browsers you need to worry about.
Notice that getElementById is a method of the document object. Many of the methods used to
access the page are found on the document object.

By Tag Name
document.getElementsByTagName works in much the same way as getElementById, except that it takes
a tag name (a, ul, li, etc) instead of an ID and returns a NodeList, which is essentially an array of
the DOM Elements.
By Class Name
document.getElementsByClassName returnsthe same kind of NodeList as getElementsByTagName,
except that you pass a class name to be matched, not a tag name.

By CSS Selector
A couple of new methods are available in modern browsers that make selecting elements easier
by allowing the use of CSS selectors. They are document.querySelector and document.querySelectorAll.

var pageHeader = document.querySelector('#header');


var buttons = document.querySelectorAll(.btn);
querySelector,
like getElementById, returns only one element whereas querySelectorAll returns a
NodeList. If multiple elements match the selector you pass to querySelector, only the first will be
returned.

Events and Callbacks


In the browser most code is event-driven and writing interactive
applications in JavaScript is often about waiting for and reacting
to events, to alter the behavior of the browser in some way.
Events occur when the page loads, when user interacts (clicks,
hovers, changes) and myriad other times, and can be triggered
manually too.
To react to an event you listen for it and supply a function
which will be called by the browser when the event occurs. This
function is known as a callback.
Here’s a group of the things needed to listen for an event; the callback function, an element and
the call to listen for an event:

var handleClick = function (event) {


// do something!
};
var button = document.querySelector('#big-button');
button.addEventListener('click', handleClick);
addEventListener is
a method found on all DOM elements. Here it’s being called on an element
saved in the button variable. The first argument is a string - the name of the event to listen for.
Here’s it’s click - that’s a click of the mouse or a tap of the finger. The second is
the callback function - here it’s handleClick.
Unfortunately, Internet Explorer does not support addEventListener in versions earlier than 9.
Instead attachEvent must be used.

button.attachEvent('onclick', handleClick);
Notice that it requires onclick, not just click. You’ll find this is the same for most events. It’s
things like this that caused the creation of libraries like jQuery (which we’ll come to) - they help
you so that you don’t have to care that the way of listening for events is different across
browsers.
Data about a particular event is passed to the event callback. Take a look at handleClick, declared
above. You can see its argument: event - it’s an object whose properties describe what occurred.
Here’s an example event you might see into a click event callback like handleClick. There are lots
of properties giving you an idea of where the event occurred on the page (like pageX and offsetY) -
these are slightly different because they depend on the reference point used to measure from.
You can also see the target which is a reference to the node that was clicked.

{
offsetX: 74,
offsetY: 10,
pageX: 154,
pageY: 576,
screenX: 154,
screenY: 489,
target: h2,
timeStamp: 1363131952985,
type: "click",
x: 154,
y: 395
}

AJAX
In the early years of the web things were simple — a page was
text, perhaps with styling, and it contained links to other pages.
To get new content you moved from one page to the next. But as
developers got more ambitious with the web, attempting to build
interactive (“native-like” applications), it was obvious that there
needed to be a way to load new content into a page without a
full reload.
To retrieve new content for a page, like new articles on an
infinite-scroll site or to notify you of new emails, a tool called
an XML HTTP Request (XHR) is used. Web apps that do this
are also called AJAX apps, AJAX standing for Asynchronous
JavaScript and XML.
Almost all sites that pull in new content without a page reload (like Facebook, Gmail, Google
Maps etc) use this same technique. In fact, it was Microsoft developing Outlook Web Access
who originally created the XMLHttpRequest.

XML HTTP Request


So what does an XMLHttpRequest look like?

var req = new XMLHttpRequest();


req.onload = function (event) { . . . };
req.open('get', 'some-file.txt', true);
req.send();
The first thing to do is create a new XMLHttpRequest request, using the new keyword, and
calling XMLHttpRequest like a function.
Then we specify a callback function, to be called when the data is loaded. It is passed
information about the event as its first argument.
Then we specify how to get the data we want, using req.open. The first argument is the HTTP
method (GET, POST, PUT etc). Next is the URL to fetch from - this is similar to
the href attribute of a link.
The third is a boolean specifying whether the request is asynchronous - here we have it true, so
the XMLHttpRequest is fired off and then code execution continues until a response from the server
causes the onload callback to be fired.
The asynchronous parameter defaults to false - if it’s false, execution of the code will pause at
this line until the data is retrieved and the request is called synchronous. Synchronous
XMLHttpRequests are not used often as a request to a server can, potentially, take an eternity.
Which is a long time for the browser to be doing nothing.
On the last line we tell the browser to fire off the request for data.
Using an XMLHttpRequest you can load HTML, JSON, XML and plain text over HTTP and
HTTPS, and it also supports other protocols like FTP and file. All in all, they’re very useful for a
whole range of tasks involved in developing JavaScript apps.

AJAX and Libraries


The AJAX technique has been developed to the point now where single-page apps are possible -
one main request loads JavaScript code which then loads, asynchronously, other content from the
server. Whole libraries and frameworks have been built to help do so, and we’ll take a look at
them later.

JSON
JSON — JavaScript Object Notation — is a set of text
formatting rules for storing and transferring data in a machine
and human readable way. It looks a lot like the object literal
syntax of JavaScript, and it is from there JSON originates.
But JSON is not JavaScript. Officially it’s a totally different language with its own spec but it
plays such a big part in JavaScript development that it’s important to cover.
Here’s some JSON:

{ "name": "Yoda", age: 894, "lightsaber" : { "color": "green" } }


Like in JavaScript, the brace notation is used.
Interestingly, the above example is actually valid JavaScript.
JSON is used to transfer information - between your browser to a server, or saved in text files for
retrieval later - because it’s simply text. That means you can’t store complex data like a function,
but you can store arrays, objects containing simple data, strings and numbers.
JSON is taking over from XML as the data-transfer format of the web, and many new web APIs
are written exclusively serving JSON, which can mean that you can be using AJAX technology
to grab JSON. But AJAJ ain’t so catchy.
Advertise Here!On a long-established, well-read, well-respected web development resource.

Using JSON
Data is either converted to or from JSON, using methods called stringify and parse respectively.
JSON is an object available in pretty much all modern browsers but there are ways of adding to a
browser that doesn’t have it.

var jsonString = JSON.stringify({


make: "McLaren",
model: "MP4-12C",
miles: 5023
});
JSON.stringify converts an object into a JSON string. In this example, jsonString becomes {"make":
"McLaren", "model": "MP4-12C", "miles": 5023 }.

var car = JSON.parse(jsonString);


The string can then be converted back to a JavaScript object using JSON.parse. car is now usable
as a normal JavaScript object, so you can set its properties:

car.model = "P1";

Scope
Scope is the term used to mean variable visibility — a
variable’s scope is the part of your code that can access and
modify that variable. JavaScript has function scope — but what
does that mean and how is it different to other languages?
Scope is, in many programming languages, dictated by the block in which the variable was
declared. A block, in C-like languages, is anything between two curly braces, or indentation in a
language like Python. For example, the b variable below is not available outside the curly braces
in which it was declared:

var a = 10;

if (a > 5) {
var b = 5;
}

var c = a + b; // Wouldn't work!


Global variables — that is, variables that can be read and modified anywhere in your application
— are not good because they can expose security issues and make code much harder to maintain.
Remember that code is read much more than it’s written. When reading code, if you can’t
determine where a variable came from and what its potential values are, there’s a problem.
So it’s best to limit the scope of a variable as much as possible, making it visible to as few parts
of your code as possible.
New Examples Section!See all of this code stuff in action, and play around
with it.

Function scope
JavaScript does things a little differently. It uses function scope. This means that variables are
not visible outside of the function in which they were declared. If they are not declared inside a
function then they are available globally.
The example below demonstrates that a variable is only visible inside the function in which it
was declared. The doSomething function is the variable a’s scope.

var doSomething = function () {


var a = 10;
};

doSomething();

console.log(a); // a is undefined
Comparing this to the block scope example above, you can see that, in JavaScript, b is available:

var a = 10;

if (a > 5) {
var b = 5;
}

var c = a + b; // c is 15

Child scopes
Variables are available in child scopes of their own scope. For example, doSomethingElse is a
child of doSomething, so a is visible inside doSomethingElse.

var doSomething = function () {


var a = 10;
var doSomethingElse = function () {
console.log(a); // a is 10
};
doSomethingElse();
};

doSomething();
Functional scope is a very powerful tool for creating elegant code, as we’ll see, but it can take
some time to get your head around.

jQuery
The set of tools used to allow modification and control of the
DOM are a bit of mess because they differ across browsers,
generally for historical reasons. To make your job easier, a
number of libraries have been created that hide these
differences, providing a more uniform way of interacting with
the DOM. Often they also provide AJAX functionality, taking
the burden of that complexity away from you.
jQuery is far and away the most popular DOM library and it is
used on a huge number of websites.
By the way, the way you interact with the DOM (or any service that you use via code) is called
an Application Programming Interface or API.
jQuery has a very distinctive syntax, all based around the dollar symbol. Here’s some:

$('.btn').click(function () {
// do something
});
This code attaches a click handler to all elements with a class of btn. This selector syntax is core
to jQuery.

Link To Us!If you've found HTML Dog useful, please consider linking to us.
jQuery is added to a page by simply including it as a file using a script element. Download it from
jquery.com, or include it from a Content Delivery Network (CDN) such as CDNJS:

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
In the following pages we’ll be taking a look at jQuery for selecting and manipulating
elements, AJAX and at some of its other useful tricks.
It’s not always the best idea to use a library, and it’s best to choose whether to use a framework
based on the specific project. For example, jQuery is a large file to introduce to a page and slow
the downloading of that page, particularly on mobile browsers with potentially weak
connections.

jQuery: DOM API


Selecting elements and interacting with the DOM are things
you’ll probably use jQuery for the most. Luckily it’s really easy
to do because the syntax for choosing an element, or set of
elements, is exactly the same as element selection in CSS.
jQuery also makes performing actions on many elements at the
same time simple, which is incredibly useful.
In the example below $('.note') selects all the elements with a class of note on the page and then
we set the background of all of the note boxes to red and their heights to 100px.

$('.note').css('background', 'red').height(100);
jQuery uses a really neat chainable syntax that allows code like the above. This works because,
for any kind of “setting” method, jQuery returns the same thing as the selector function (“$”)
does: $ is a function that returns a jQuery wrapper around an element. .css is a method of that
jQuery wrapper and it too returns the same wrapper. .height sets the height (duh) of the element
selected, and of course there’s an equivalent for width.
Advertise Here!On a long-established, well-read, well-respected web development resource.

Getters and setters


In the above example we used .css and .height to set the value of the element but these methods are
also getters. Calling .height without any value returns the current element’s height and
calling .css with just a CSS property name retrieves the property’s value.

var currentHeight = $('.note').height(),


currentColor = $('.note').css('color');
If you’ve got more than one element selected (you have lots of note elements, say) a getter will
retrieve the value for the first of them.

Context
It’s sometimes useful to limit the area of the DOM from which an element can be selected. The
area of the DOM used is also known as a different context.
To tell jQuery which area you want to select from you pass a second argument that can be
a DOM element, a string selector (selecting an element that jQuery will find and use) or
a jQuery object. jQuery will only search within this context for your selector.
Here’s an example. Notice that the variables that are used to store jQuery objects begin with
a dollar. This a convention to help you and readers of your code understand that it’s a jQuery
object being saved.

var $header = $('header'),


$headerBoxes = $('.note', $header);

jQuery: AJAX
jQuery has some AJAX helper methods that save time and are
much easier to read. They are all properties of
the $ variable: $.get, $.post, and $.ajax.
$.ajax is
the main method, allowing you to manually construct your AJAX request - the others are
shortcuts to common configurations, like getting data or posting it.
Here’s an example that gets some data from a server:

$.ajax({
url: '/data.json',
method: 'GET',
success: function (data) {
console.log(data);
}
});
You can see that a configuration object is used to tell jQuery how to get the data. The basics are
supplied: a URL, the method (which actually defaults to get) and a function to be called when the
data is retrieved, named the success callback.

Link To Us!If you've found HTML Dog useful, please consider linking to us.

$.get
This example is just getting some data and, because this is a very common activity, jQuery
provides a helper: $.get.

$.get('/data.json', function (data) {


console.log(data);
});
You can also provide an error callback, which will let you know if something goes wrong and
the server can’t be reached:

$.get('/data.json', function (data) {


console.log(data);
}).fail(function () {
// Uh oh, something went wrong
});

$.post
Sending data to a server is just as easy, using the $.post method. The second argument is the data
to be sent - it can be almost anything except a function: jQuery will figure out how to send it for
you. How convenient!

$.post('/save', { username: 'tom' }, function (data) {


console.log(data);
}).fail(function () {
// Uh oh, something went wrong
});

$.ajax
Of course, if you want more control over how data is sent, use $.ajax to set the request up
manually.

$.ajax({
url: '/save',
method: 'POST',
data: { username: 'tom' },
success: function (data) {
console.log(data);
}),
error: function () {
// Uh oh, something went wrong
}
});

jQuery: Other Tricks


jQuery also helps you out with other common tasks, particularly
where things are inconsistent across browsers.
DOMContentLoaded
Sometimes you will want to run JavaScript only when the DOM is loaded and ready (but before
stylesheets are fully loaded) - for example, to move elements to a different location in the page,
or create new ones. We can do this in pure JavaScript (although this will not work in all
browsers):

var doSomething = function (event) { . . . };

window.addEventListener('DOMContentLoaded', doSomething);
But we can do it more easily with jQuery, and it will work cross-browser:

$(window).ready(doSomething);
This can be shortened further to:

$(doSomething);
In all the above examples, doSomething is a JavaScript function.

Link To Us!If you've found HTML Dog useful, please consider linking to us.

Load
In other situations it’s better to wait for the page to fully load - that is, when all stylesheets and
images have been downloaded.
To do this without jQuery, listen for the load event on the window:

window.addEventListener('load', doSomething);
But it’s even easier with jQuery:

$(window).load(doSomething);

Type checking
Finding out what kind of data is stored in a variable in JavaScript is awkward at best so jQuery
provides some tools to help you out:

$.isArray([1, 2, 3]);

true

$.isFunction(function () { });

true

$.isNumeric(10);

true

$.isPlainObject({ name: 'Tom' });

true
Object-Oriented Code
Humans are good a categorizing. Objects are a way to
categorize behavior and data, making large amounts of code
easier to design and think about. In fact, object-
oriented programming can be found in many languages used to
build all kinds of software and is considered a very good way to
write code.
We’ve already looked at objects in JavaScript - they’re collections of named properties and
methods, and they can be created on the fly using the object literal syntax:

var user = {
name: "tom",
say: function (words) { alert(words); }
};
One reason using objects to hold data is useful is that, as mentioned, human brains are very good
at categorizing things: a boat; a chair; a moose. Creating objects in code helps you to think about
how the different parts of your code fit and (hopefully) work together.
In a large application you may have a great number of objects interacting with each other.
Remember that objects are a grouping together of properties (like name) and methods (like say)?
This grouping of data and behavior into one entity is called encapsulation.
A powerful tool available to you when building applications using objects is called inheritance.
This is where an object inherits properties and methods from another object. An object can alter
the properties and methods it inherits and add additional properties and methods too.
So, for example, you could create a moose object that inherits behavior from a mammal object.
The moose could alter the mammal’s furriness, for example. You could then create
a pangolin object that also inherits from a mammal. But, of course, pangolins aren’t furry, and
they might have a different scaliness property.

Link To Us!If you've found HTML Dog useful, please consider linking to us.

How do objects inherit?


JavaScript uses prototypal inheritance. This means that, when an object inherits from another,
the parent object is known as the child’s prototype.
There are a couple of other things to know: every object maintains a reference to its prototype
and every object inherits from the global object object.
When you ask for a property of an object, JavaScript looks for the property on that object. If it
doesn’t find it there, it follows the link to the object’s prototype and looks for the property there.
It continues this, up the prototype chain until it finds it, or it returns undefined.
In other words, an object inherits properties and methods by maintaining a link to another object
from which it wants to inherit. Multiple objects can inherit from one single object, but one single
object cannot inherit from multiple other objects, although it can inherit from an object that
inherits from another.

In practice
There are many ways to achieve inheritance in JavaScript. The most commonly used is
the constructor pattern. In this pattern, a function called a constructor is used to create new
objects. Constructors are used in combination with the new keyword to create objects.
Here’s an example constructor. Note the capital letter on Person - this is an important
convention. Generally, in JavaScript, if it’s got a capital first letter, it’s a constructor and should
be used with the new keyword.

var Person = function (name) {


this.name = name;
};
Now you can use the new keyword to create Person objects:

var tom = new Person('tom');


This produces an object like this:

{
name: "Tom"
}
In the constructor pattern you manually create the object from which the new objects will inherit
by adding properties and methods to the prototype property of the constructor function. Like this:

Person.prototype.say = function (words) {


alert(this.name + ' says "' + words + '"');
};
Now, objects created from the constructor will have the say method.

var tom = new Person("tom");


tom.say("Hello");

// Produces an alert: tom says "Hello"

This is just the start


Inheritance and object-oriented programming are big, complex areas that whole books are
written about. If you’d like to know more there are a few great resources out there.
If you’d like to know more about the new keyword, check out the thread on Stack Overflow. For
a slightly more detailed article about constructors, check out Constructors considered mildly
confusing.

Creating Elements
Creating elements using HTML tags isn’t the only way to do it
— in fact it’s possible to create, modify and insert elements
from JavaScript.
Here’s an example that creates a div, adds some text to it and appends it as the last element in the
body:

var div = document.createElement('div');


div.textContent = "Sup, y'all?";
div.setAttribute('class', 'note');
document.body.appendChild(div);
So document.createElement is used with an HTML tag to create the element. The textContent is then
modified and then the class attribute is modified using setAttribute. This could also be used to add
a data attribute or any other kind of attribute, like you can in HTML! Finally the element is
appended to the body using the body element’s appendChild method.
It’s essentially equivalent to <div class="note">Sup, y'all?</div>.
In fact, all elements have the appendChild method, so having done the above it’s possible to do the
following:

var span = document.createElement('span');


span.textContent = "Hello!";
div.appendChild(span);
The span will be added to the end of the div element.
New Examples Section!See all of this code stuff in action, and play around
with it.
Unfortunately, the textContent property used is not supported by all browsers. Internet Explorer
(sad face) only supports an equivalent property called innerText. Other browsers
support innerText too but in the interests of web standards it’s best to see which property the
element supports, and use that:

var span = document.createElement('span');


if (span.textContent) {
span.textContent = "Hello!";
} else if (span.innerText) {
span.innerText = "Hello!";
}

Removing an element
Removing elements is just as fun. Each DOM element has a property that’s actually the DOM
element’s parent. To remove an element, you call the removeChild method of the parent, passing
the child element you want to remove. Something like this:

div.parentNode.removeChild(div);
Simple, eh?

Creating with jQuery


The other alternative is to use jQuery’s element creation syntax. This example does the same as
the above examples combined:

var div = $('<div/>').text("Sup, y'all?").appendTo(document.body);


$('<span/>').text('Hello!').appendTo(div);

Canvas
The HTML 5 specification has introduced a slew of new and
exciting technologies to the web. Here we’ll expand on just one:
the Canvas API. It’s for drawing pretty, whizzy things.
Canvas is a new DOM API for drawing on a 2- or 3-dimensional (you guessed it) canvas. What
follows just looks at the 2D version, but the 3D technology is called WebGL and there are some
incredible things being done with it.
The first thing to know is that canvas is a new element in the HTML 5 specification. To begin
drawing on the canvas, you grab hold of it and retrieve a particular context - either 2d or webgl:

var canvas = document.querySelector('canvas'),


ctx = canvas.getContext('2d');
From there you can begin drawing, filling and stroking shapes and text on the canvas. Here’s an
example that draws a simple square on a canvas.

<canvas></canvas>

<script>
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
ctx.fillRect(10, 10, 10, 10);
</script>
Try this out on a page to see a little black square!
The getContext function retrieved the correct context, which is an object whose methods are used
to draw, fill and generally modify the canvas. Above we’re using fillRect, which takes
the x and y position of the top left corner of the rectangle as the first two arguments, and
the width and height dimensions as the latter two.

New Examples Section!See all of this code stuff in action, and play around
with it.

Animation
canvas works a bit like a real canvas - pixels are drawn and layered on top of each other until you
erase - clear - them. This means that if you want to animate something moving across a canvas
you have to repeatedly clear the canvas (or a section of it) and redraw the scene.
In the next example we’ve animating the square bouncing around the canvas, which automatically
resizes to fill the screen. loop is the business part of the code. The clearRect function is used to
clear the entire canvas before each frame.

var canvas = document.querySelector('canvas'),


ctx = canvas.getContext('2d');
var resize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};

window.addEventListener('resize', resize);

window.addEventListener('load', function () {

resize();

var pos, vel;


pos = {
x: 10,
y: 10
};
vel = {
x: 1,
y: 1
};

var loop = function () {


ctx.clearRect(0, 0, canvas.width, canvas.height);
pos.x += vel.x;
pos.y += vel.y;
if (pos.x < 5 || pos.x > canvas.width - 5) {
vel.x *= -1;
}
if (pos.y < 5 || pos.y > canvas.height - 5) {
vel.y *= -1;
}
ctx.fillRect(pos.x - 5, pos.y - 5, 10, 10);
};

setInterval(loop, 1000 / 60);


});
There’s lots to explore with canvas, this was just a very shallow look at it. There are many
specialized resources on the web so, to find out more, Google is your best friend.

Local Storage
When building more complex JavaScript applications that run in
a user’s browser it’s very useful to be able to store information
in the browser, so that the information can be shared across
different pages and browsing sessions.
In the recent past this would have only been possible
with cookies - text files saved to a user’s computer - but the way
of managing these with JavaScript was not good. Now there’s a
new technology called local storage that does a similar thing,
but with an easier-to-use interface.
Unlike cookies, local storage can only be read client-side — that is, by the browser and your
JavaScript. If you want to share some data with a server, cookies may be a better option.
To save some data, use localStorage.setItem.

localStorage.setItem('name', 'tom');
The first argument is the identifier you’ll later use to get the data out again. The second is the
data you want to store.

Link To Us!If you've found HTML Dog useful, please consider linking to us.
Getting back out again is simple — just pass the identifier to localStorage.getItem.

var name = localStorage.getItem('name');


Local storage can only save strings, so storing objects requires that they be turned into strings
using JSON.stringify - you can’t ask local storage to store an object directly because it’ll store
“[object Object]”, which isn’t right at all!
That also means the object must be run through JSON.parse on the way out of local storage. You
can see this in the example below.

// Object example
localStorage.setItem('user', JSON.stringify({
username: 'htmldog',
api_key: 'abc123xyz789'
}));

var user = JSON.parse(localStorage.getItem('user'));


Browser support for local storage is not 100% but it’s pretty good - you can expect it to work in
all modern browsers, IE 8 and above, and in most mobile browsers too.

Errors and Exceptions


Errors are often used to notify another piece of code that
something went wrong when trying to carry out a task and that
error may then be passed on to the user.
When errors are created — thrown — they interrupt the code that’s currently being run, unless
they are caught.
For example, you can force an error to be thrown by giving JSON.parse invalid data:

JSON.parse("a");

// Produces a SyntaxError

You can account for exceptions being thrown using a construct called a try-catch. It looks like
this:

try {
JSON.parse("a"); // Produces a SyntaxError
} catch (error) {
// Handle the error
alert(error.message);
}
If an error is thrown in the try block it doesn’t prevent continued code execution - the error is
passed into the catch block for you to deal with. Here, for example, you could tell the user that the
JSON that was passed in was invalid.
The error passed to the catch block (like a function) is an object with a message property you can
use to see what went wrong.
In almost all cases you’ll want to ensure your code handles errors gracefully. It’s worth learning
when errors are likely to occur so that you can defend your code against them.
Advertise Here!On a long-established, well-read, well-respected web development resource.

Creating errors
It’s possible to generate your own errors for someone else to deal with. This is done using
the throw keyword:

throw new Error("I hungry. Fridge empty.");

Defensive code
Errors are most common at the front line where data from outside your code is brought in, and so
those are the areas you need to be most careful.
Try-catch blocks are one way of handling errors, but you can also check the type of some data
and provide sensible defaults if you do receive ill-formatted data. Being defensive in your code is
a good way of avoiding errors.

Regular Expressions
Regular expressions are another type of data in JavaScript,
used to search and match strings to identify if a string is a
valid domain name or to replace all instances of a word within a
string, for example.
Regular expressions have their own syntax and often you’ll need to consult a regular expression
reference if you’re doing something complex. Just search the Internet for what you need!
The following is a very high-level overview of a complex area, going through some simple
examples to show how to do it in JavaScript.

Creating regular expressions


Like with objects and arrays, there is a regular expression literal syntax designated by two
forward slashes. Everything between is the expression:

var regex = /^[a-z\s]+$/;


This expression matches strings that are made of lowercase letters and whitespace from
beginning to end. The caret (“^”) indicates the start of the string, and the brackets indicate that
anything between the opening and closing brace - letter a to z (“a-z”), lowercase, and white-
space, indicated by the special “\s” character - can be repeated one or more times up to the end of
the string, indicated by the dollar (“$”) symbol.
Advertise Here!On a long-established, well-read, well-respected web development resource.
Strings have a few useful methods that accept regular expressions; here’s a look
at match and replace:

var lowerCaseString = 'some characters';

if (lowerCaseString.match(regex)) {
alert('Yes, all lowercase');
}
match produces a truthy value if the regular expression matches the string
(lowerCaseString) match is called on. The string matches, so execution drops into the if statement to
show an alert.
Regular expressions can also be used to replace text:

var text = "There is everything and nothing.";

text = text.replace(/(every|no)thing/g, 'something');

// text is now "something and something"

This expression matches the word “everything” and the word “nothing” and replaces all
occurrences of them with the word “something”. Notice the “g” after the closing forward slash
(“/”) of the regular expression - this is the global flag that means the expression should
match all occurrences, rather than just the first, which is what it does by default.
Flags always go after the closing slash. The other flag you might need to use is the case-
insensitive flag. By default, regular expressions care about the difference between uppercase and
lowercase letters, but this can be changed using the “i” flag.

var text = "Everything and nothing.";

text = text.replace(/(every|no)thing/gi, "something");

// text is now "something and something"

Closures
A closure is a function that returns a function. The function that
is returned (the inner function) is created inside the called
function (the outer) so - due to the scoping rules we’ve seen -
the inner has access to the variables and arguments of the outer.
Closures are a powerful tool but can be tricky to understand. Mastering them, however, will
allow you to write some very elegant code.
Here’s an example:

var saver = function (value) {


return function () {
return value;
};
};

var retriever = saver(10);

alert(retriever());

10

The saver function returns a function that, when called, retrieves the value that was passed into
saver. The inner can do so because it was created in the scope of the outer and functions created
in a particular scope retain access to variables in the scope even if they are called outside of it.
Advertise Here!On a long-established, well-read, well-respected web development resource.
One way to use closures is for creating functions that act differently depending on what was
passed to the outer function. For example, here’s an add function. The value passed to the outer
function is used to add to values passed to the inner.

var add = function (a) {


return function (b) {
return a + b;
};
};

var addFive = add(5);

alert(addFive(10));

15
The inner, here saved as addFive, has access to a when it is called because it was created in the
same scope as a. The inner adds a and b and returns the result.
In the above example, the inner is saved as addFive because it adds 5 to anything passed to it. A
different adding function, using strings, could be created in the same way:

var hello = add('Hello ');

alert(hello('tom'));

Hello tom

Node.js
Much of the code we’ve seen so far has been with a web
browser in mind, using DOM APIs that are only available in that
environment. But JavaScript has found its way to the other side
of the client/sever divide in the form of Node.js (also known as
just Node).
Node is a platform for building servers in JavaScript, built on Google’s V8 JavaScript engine.
V8 is also found in the Chromium browser project and derivatives like Google Chrome.
If you have used preprocessors like PHP then Node may take some getting used to, but the main
thing to remember is that it works like JavaScript in the browser: idling until an event occurs,
responding to that event and returning to idle.

Install
You can grab Node from nodejs.org. You’ll get npm in there too, which is the Node Package
Manager, used to install others’ modules to make developing things easier.
Advertise Here!On a long-established, well-read, well-respected web development resource.

Example
Node comes with a core set of modules, one of which is “http”, used to set up a web server.
Here’s a simple HTTP server example that serves one page to all requests:

var http = require('http');

var server = http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
})

server.listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');


We grab the “http” module then create a server with a single callback function that serves all
requests and then set it up to listen on localhost port 1337.
From there things get a whole lot more interesting. Node is used to do everything from clusters
of servers to development tools like Grunt. A number of tools and utilities for web development
use Node, so it’s definitely something that’s worth getting familiar with!

JS Apps
These days JavaScript is being used to build large-scale web
applications and the web is maturing as a platform for doing so.
These apps have the advantage of being able to be highly
interactive and responsive, requiring fewer page loads and
HTTP requests.
Ideas are being taken from the software engineering world on how to build such applications, so
here’s a few ideas on how to do it before a look at some JavaScript frameworks designed to
assist building larger apps.

Modularity
A key concept in software engineering is the idea of modularity in code. Separating out the key
functionality of your app improves its maintainability and has a number of development
advantages.
For example, in a modular system a component can be swapped out at little cost, so long as the
interface between the components remains the same. Similarly, different components can be
worked on in isolation from each other, which is beneficial for development time and human
resource management.
Modules can be connected in a number of different ways - one way is with modules
communicating only with a central event and resource management module, sometimes referred
to as a sandbox, and not communicating directly with each other. A module can publish a
notification about an event occurring without caring who or what else will act on it. This means
that if one component ceases to function the others may continue, and that a new module can be
easily added without affecting the others.
If you want to begin building modular apps, a library called RequireJS is a good place to start.
Link To Us!If you've found HTML Dog useful, please consider linking to us.

MVC Architecture
Model-View-Controller (MVC) architecture is a way of structuring code within an application.
A model is concerned with the data in your app; the view with displaying or outputting data and
the controller with the business logic and coordinating the models and views. An app might
have many of all three.
For example, you might have a User model that is responsible for retrieving information about a
user. Then you’d have a Login controller that managed when to show a log-in screen to a visitor.
The LoginView would be responsible for showing the screen and handling form submission, the
data from which would be passed to the Login controller through to the User model.
As with any system there are a number of variations on this, and a number of client-side
frameworks have addressed this idea in JavaScript. We’ll take a quick look at
two: Backbone and Angular.

Backbone
Backbone.js (aka Backbone) is designed to add structure to
client-side applications, to avoid a spaghetti-code mess.
In the words of Backbone.js:
Backbone.js gives structure to web applications by providing models with key-value binding and
custom events, collections with a rich API of enumerable functions, views with declarative event
handling, and connects it all to your existing API over a RESTful JSON interface.
Models are where you keep your data, and in Backbone they are special JavaScript objects
created from a Backbone’s built-in Model, optionally extended by you to add functionality.
Making a Model looks something like this:

var jedi = new Backbone.Model({


name: 'Yoda',
age: 874
});
You can then connect this model up to a View that displays it to the user, via a template. The
template is just HTML with special tags or other syntax used to indicate where the model’s data
should go.
A view looks something like this, including adding it to the page and rendering it.
var jediView = new Backbone.View({
model: jedi,
tagName: 'div',
jediTpl: _.template($('#jedi-template').html()),
render: function () {
this.$el.html(this.jediTpl(this.model.toJSON())));
return this;
}
});

jediView.$el.appendTo('body');

jediView.render();
A template, often kept in a script element with a type of “template”, contains the HTML that the
view should use. For the above example, it might look something like this:

<script type="template" id="jedi-template">


<h1><%- name %></h1>
<h2><%- age %></h2>
</script>

Link To Us!If you've found HTML Dog useful, please consider linking to us.
Backbone is a very large, well-used and mature project, and covering it in any depth is way
beyond the scope of this tutorial. If you’d like to learn more, Addy Osmani’s freely available
book Developing Backbone.js Applications is a great resource.
One thing to consider about Backbone is that it’s dependent on two other JavaScript
libraries: jQuery and Underscore. This makes it quite a heavy dependency to have in your
project, and that’s something worth taking into account when deciding whether to use it. Mobile
browsers may struggle to download all that code, making your site unusable.

Angular
AngularJS is an open-source client-side JavaScript framework
that uses HTML as its templating language. It’s notable for it’s
philosophy that declarative programming is better than
imperative programming for wiring up user interfaces and
creating modular components.
Angular is MVC but it works quite differently from Backbone.
Templates and views in Angular are analogous, and are just regular HTML with some added
sugar. In fact, you can put together a (very) simple Angular app without a single line of
JavaScript:

<input ng-model="name">

<h1>Hello {{ name }}</h1>


The ng-model attribute on the input element connects the value of the input to a model called
“name”. Angular creates this model for us; it doesn’t need to be declared elsewhere. Then, in
the h1, we bind to the value of the “name” model. When you update the input, the h1 will update
too.
When you want to build something useful in Angular, you use a controller, which is just a
JavaScript function:

var AppCtrl = function ($scope) {


$scope.name = "Yoda";
};

Link To Us!If you've found HTML Dog useful, please consider linking to us.
A controller has a scope, which is an area of DOM it has access to. Giving a controller a scope
looks like this:

<div ng-controller="AppCtrl">
<input ng-model="name">
<h1>Hello {{ name }}</h1>
</div>
A model exists within a controller’s scope, so in the above example the “name” model would be
set to “Yoda” by default, but the input would update the model and the h1 as you typed.
You’ll notice the $scope variable that the controller takes as an argument, but that seems to come
from nowhere. This is injected into the controller using a system called dependency injection.
It’s a complex area, but is a useful tool for building modular apps.
Angular doesn’t depend on anything in the page, and so the file-size footprint tends to be smaller
than Backbone. If you’re worried about your HTML validating then Angular supports using data
attributes instead of the ng attributes used above. For example, data-ng-controller.

You might also like