JavaScript plus a dash of JQuery
A Sensible Introduction to Coding with JavaScript
Won't somebody help Mrs Potts!?
By Nicholas Johnson
Document version 1.0.1
(c) 2014 Nicholas Johnson

Won't somebody help Mrs Potts!?
By Nicholas Johnson
Document version 1.0.1
(c) 2014 Nicholas Johnson
Hello there new programmer! If you've never programmed before, you're in for a treat because this is the section for you! In this section we're going to be covering the very basics of JavaScript from the ground up. These are the fundamentals that you will need to know to do the fancy schmancy stuff that you're probably quite keen to get started on shortly.
We'll be creating some fun little programs, making some sandwiches, and learning a little (or a lot) along the way.
If you're already a ninja coder, you have a different set of challenges ahead of you. Javascript is rather different to what you might be used to. If you've used a language with C based syntax before, such as Java, you might feel lulled into a false sense of security by the similarities, but don't be fooled, under the hood, JavaScript is a different sort of animal.
Do feel free to skim. You should check out functions though as these are a little different from what you may be used to. You might find you have to unlearn a few things along the way.
This is the first exercise. In this exercise, we'll be saying hello to JavaScript. Of course the JavaScript won't actually hear us saying hello, unless we shout really loud…
First of all we'll need to make a web page for our script to live in. Create the following ultra simple html document and save it in a folder. Call it hello.html.
<!DOCTYPE html>
<html>
<head>
<title>Hello JavaScript</title>
</head>
<body>
</body>
</html>
Next create a document to contain your javascript. Save it in the same folder as your html and call it hello.js.
alert("Hello JavaScript, your new best friend!");
Now we need to link the two together. In the head of your html document add a script tag like so:
<script src="hello.js"></script>
(If you're an XHTML type of person, you should note that the script tag cannot be self closing. It will break in IE.)
Now open the page you just created in your web browser of choice. You should see a handy little box pop up welcoming you to JavaScript.
Tip. To open the file in a web browser, you can double click it in your exporer or finder window, or you can open Firefox and choose File -> open from the menu
The next thing we should know about is strings. A piece of text in JavaScript is called a string. It's a string of letters all attached together. We can tell it's a string because it sits between quote marks like this:
"I am a String"
Everything between the quotes is part of the string and will be treated by JavaScript as a piece of text, and not part of your program.
We can also use single quotes too like so:
'I am a String'
We can add strings together to make longer strings using the plus character:
"Hi there " + "hello"
If we need to know what's inside a string we can find out using an alert box like so:
alert("Hi there " + "hello");
One of the ways we can use strings is to help our program talk to our user. We saw this in the first example in exercise 1. We used an alert box to display the string "Hello JavaScript, your new best friend!". Strings have a whole host of uses that we'll come too soon.
Nice and simple this one. We're just going to create some strings and pop them up in little boxes.
1.
alert("Hello there JavaScript");
2.
alert("Hello there Java" + "Script");
Works? Fine.
Doesn't work? First check your HTML. Make sure you are importing the right JavaScript file.
Imagine for a moment your program is a bit like a child on a beach making a sandcastle. The child is going to need lots of raw materials to make that castle, sand, little shiny rocks, pebbles, flags, water from the sea. The child is going to need somewhere to keep all of those raw materials. He's going to need some buckets.
Variables are like JavaScript buckets. We can store things in them until we need them later, and we can use the bucket in place of the thing that's inside.
We can tell JavaScript to make a variable just by putting something in one, like this:
var greeting = "Hi there!";
alert(greeting);
We have put the string "Hi there!" inside a variable (bucket) called greeting.
We can also change the value of a variable any time, just by assigning a new value to it, so we could write:
var name
name = "Dave";
alert(name);
name = "Susan";
alert(name);
The variable called name contains first the string "Dave", and then the string "Susan". Dave is now renamed Susan.
Imagine I have a basket full of kittens, now when I hand you that basket, I'm actually handing you a bunch of kittens. This is probably a pleasant experience for you.
We can write this like this:
var basket = "kittens";
Now the basket can stand in wherever we previously needed kittens. For example, I could write:
alert('kittens');
or I could write
alert(basket);
Either way I would alert some kittens.
Variables can be called almost anything you like. Hamster, pie or cheeseOnToast are all perfectly sound variable names. The one restriction is that you can't have any spaces or maths characters in them. You can't have a variable called "cheese on toast" for instance, or a variable called five+five. This would confuse JavaScript and give it a headache.
Don't worry about giving your variables long and descriptive names. This is encouraged as it makes your code easy to read.
We can call our variables anything we like but it makes our lives easier if we give them sensible English names or common abbreviations.
Please note that when we first create a variable we must always remember to use the var keyword. If we forget it, bad things will happen. More on this when we get to Scope. For now, just remember to put them in.
Variables are like little buckets in which we can store any information we like. Let's pop a string in one, and then pop it out in an alert box.
To answer this question, first we create a variable, lets call it greeting, and assign a value of "Thanks for all the fish" to it. The variable greeting is a bucket that contains the string. We can now use it in place of the string, and alert it.
var greeting = "Thanks for all the fish";
alert(greeting);
Variables are buckets. We can use variables in place of the things they represent, so:
var question = "What's for dinner?";
var answer = "Fish";
alert(question + answer);
If we'd like to improve the output slightly we can separate the two with a space:
alert(question + " " + answer);
JavaScript is great for maths. Lets say we need to know what 3 times 5 is. We can just ask JavaScript:
alert(3*5);
So handy! You'll never need a desk calculator again. We can also combine maths with our new found knowledge of variables like so:
var slices = 12;
var slicesNeededForASandwich = 2;
var numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);
Note the that a forward slash (/) means division.
The following special characters are used when doing maths in Javascript.
There are a few more that you might need later, but these will do for now.
To test for equality in JavaScript we use ===. For example:
10 === 10;
this will come out true, because 10 is exactly the same as 10. You can also use == but you shouldn't. == in JavaScript does type conversion. This means that:
"10" == 10
will come out true. The string is equal to the number. This causes all sorts of problems, and most of the time is best avoided.
On to the exercises!
var slices = 12;
var slicesNeededForASandwich = 2;
var numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);
If you have 800 slices, you need to change the value of the slices variable like so:
var slices = 800;
var slicesNeededForASandwich = 2;
var numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);
To find out how many club sandwiches we need, all we need to do is change the value of slicesNeededForASandwich from 2 to 3. We will now get the correct answer.
var slices = 800;
var slicesNeededForASandwich = 3;
var numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);
You did it! Horray for maths! We need to do this sort of thing all the time in Javascript, whether we're working out the size of a page element, or writing a handy little VAT calculator for our online shopping cart.
Now on to functions…
Mrs. Potts is the school dinner lady. Today is the school trip, and it's her job to make sandwiches for all the children. She has to make a lot of sandwiches, and each one takes some work. The bus will be arriving soon and Mrs. Potts is worried she might not finish. Some of the children might not have enough food to eat. Hurry Mrs. Potts!
To make a sandwich Mrs. Potts has to:
We could write a program to help her to this, it might look something like this:
alert("Get bread");
alert("Spread butter");
alert("Spread jam");
alert("Cut off crusts");
alert("Put in a little bag");
Questions
This is all very well, but Mrs. Potts has to make 40 sandwiches and we've only made one. To make 40 could take a lot of typing. What if there was a way to help her by wrapping up all the actions needed to make one sandwich into a single reusable function, something we could use over and over 40 times, 100 times even. Well…
Lets make a few changes to our program above.
var makeSandwich = function() {
alert("Get bread");
alert("Spread the butter");
alert("Spread the jam");
alert("Cut off the crusts");
alert("Put in a little bag");
};
makeSandwich();
What have we done here? Well, you may have noticed that we've created a new variable called makeSandwich.
The variables we have created so far have contained strings or numbers, see the section on variables if you need a refresher, but variables are buckets remember and they can hold any type of thing. In this case we have said that the makeSandwich variable should be equal to a new type of thing called a function.
A function is a little ball of javascript, all wrapped up neatly so that we can use it again and again. After creating our function and assigning it to the makeSandwich variable, we can call it by writing:
makeSandwich();
The parenthesis (brackets) mean that we want to run the variable as a function. We can run the function as many times as we like. Just call makeSandwich() again and again, as many times as we need it.
This is all excellent, but oh dear, Mrs. Potts has just remembered that some of the children have asked for Marmite sandwiches because they are allergic to jam. Our function can only make jam. What will we do? Will the children still go hungry?
What if there was a way to tell our function what filling we want? Thankfully there is using parameters. Let's change our program like so:
var makeSandwich = function(filling) {
alert("Get bread");
alert("Spread the butter");
alert("Spread the " + filling);
alert("Cut off the crusts");
alert("Put in a little bag");
};
makeSandwich("marmite");
makeSandwich("jam");
makeSandwich("squeezy cheez");
See, we have changed our function and made it accept a parameter called filling. filling is a variable, a bucket. It is available anywhere inside the function body, that is between the {curly braces}. It can hold anything, even sandwich filling. We didt his when we wrote: var makeSandwich = function(filling).
Further down in our code we call makeSandwich("marmite"); Here we are passing the string "marmite" to our function. It will be assigned to the variable called filling and will be available to our function when it runs.
Questions
Poor Mrs Potts. She's just remembered that some of the children are allergic to milk. If they eat butter they may go into anaphylactic shock. She needs to make some of her sandwiches with margarine. Things keep getting worse and worse for Mrs Potts, she looks like she might cry. Fortunately, you are here to help her. We can extend our sandwich function to accept two parameters.
var makeSandwich = function(filling, spread) {
alert("Get bread");
alert("Spread the " + spread);
alert("Spread the " + filling);
alert("Cut off the crusts");
alert("Put in a little bag");
};
makeSandwich("marmite", "butter");
makeSandwich("jam", "margerine");
makeSandwich("squeezy cheez", "butter");
Now we are passing in two parameters, one called filling and one called spread. Filling comes first, spread comes next. When we call the function, we pass in a filing, then a spread and those values get assigned to the filling and spread variables inside the function body, i.e. everywhere between the {curly braces}.
Questions
So we have created a make sandwich function, and passed it some ingredients. We have control over our function.
At the moment though, all our function does is bung the various stages of sandwich making up in alert boxes as it goes along. What if we don't want alert boxes, what if we want to output them to the console instead, or turn them into a web page? Mrs Potts doesn't like a fuss.
It would be sort of handy if, instead of just alerting the sandwich stages, the makeSandwich function could make the sandwich, then just hand us the completed sandwich back, perhaps as a string, sort of like a sandwich machine. Then we could choose what to do with our sandwich, alert it, add it to a pile of other sandwiches, feed it to a child, etc…
To do this, we need to understand about return values. When we use the return keyword in a function, the value that we ask to be returned is sent back out of the function.
Observe:
var makeSandwich = function(filling) {
return "A sandwich loving made with " + filling;
};
alert( makeSandwich("tofu mayonnaise") );
See? Our make sandwich function now makes a sandwich and returns it.
We sometimes call this input, process and output. It's as though we have made a sandwich machine. we pass it ingredients, it processes them into a sandwich (or a string in this case), and returns it to us.
Note that we can use our sandwich machine anywhere where we might have used a string previously. JavaScript will see the function, execute it, get a string back, and then just act as though there was a string there all along.
Here's a curve ball for Mrs Potts. Please ignore this question. Definitely don't try and do it yet. (Tip, you'll need an if statement.)
var makeSandwich = function() {
alert("Get bread");
alert("Spread the butter");
alert("Spread the jam");
alert("Cut off the crusts");
alert("Put in a little bag");
};
makeSandwich();
makeSandwich();
makeSandwich();
makeSandwich();
makeSandwich();
var makeSandwich = function(filling) {
alert("Get bread");
alert("Spread the butter");
alert("Spread the " + filling);
alert("Cut off the crusts");
alert("Put in a little bag");
};
makeSandwich("crab pate");
var makeSandwich = function(filling, spread, breadType) {
alert("Get" + breadType);
alert("Spread the " + spread);
alert("Spread the " + filling);
alert("Cut off the crusts");
alert("Put in a little bag");
};
makeSandwich("tuna and sweetcorn", "soya margarine", "rye bread");
To solve this puzzle, we need to use an if statement. We can check to see if filling2 is present, and if it is, we can add it to the string.
var makeSandwich = function(filling1, filling2) {
var sandwich = "A sandwich with " + filling1;
if (filling2) {
sandwich += " and " + filling2;
}
return sandwich;
};
We can call this like so:
alert( makeSandwich( "marmite", "cheese" ) );
alert( makeSandwich( "marmite" ) );
A handy feature of JavaScript is that if you don't pass in a parameter, it is set to be undefined. Undefined is a special value that a variable has before anything has been put in it. It's an empty bucket.
One of the great things about undefined is that it's falsey. Falsey values evaluate to false, so we can call our makeSandwich function like this:
alert( makeSandwich("butter", "marmite" ) );
Filling2 is undefined, and so evaluates to false in the if statement. This is a very handy feature of JavaScript.
Our programs so far have been very nice, but quite linear. We can make sandwiches, but we can't decide whether or not we should be making sandwiches. Sometimes in our code we need to be able to be respond to things. We need to be able to say "what if?"
We do this using the if statement:
var daytime = true;
if (daytime) {
alert("Nice day!");
}
In this example, daytime is a variable that contains a special value. The value is true. True means yes, absolutely, do it. The opposite of true is false. False means no, never, don't do it. The code between the curly braces will only run if daytime is true. It will not run if daytime is false.
Questions
Sometimes we want to do a different thing if we didn't do the first thing. We need an else statement. Thankfully, this is easy.
var daytime = false;
if (daytime) {
alert("Nice day!");
} else {
alert("Nice night!");
}
Here the first block of code is run if daytime is true and the second block is run if daytime is false.
Questions
Sometimes we need more than 2 options. What if we wanted to say good evening and good morning too. We're going to need a little more information than just our true/false daytime variable. Let's create an hour variable to hold the hour of the day.
var morning = true;
var daytime = false;
var nightime = false;
if (morning) {
alert("Good Morning!");
} else if (daytime) {
alert("Nice day!");
} else if (nighttime){
alert("Nice night!");
} else {
alert("I just don't know what time it is!");
}
Wow, that was a little longer, but it does seem to make sense. If morning is true it does the first bit of code, else if daytime is true it does the second bit of code, else if nighttime is true it does the third bit. If none of the above are true it does the last bit of code.
Questions
These values that we're using, true and false, have a special name. They are called Boolean values, named after the wonderful Victorian English mathematician George Boole who first described them. Boolean values are actually the basis for all computing. You may have heard it said that computers use ones and zeros, and it's true. Deep inside, computers are made of vast arrays of switches, which can be either on or off, one or zero, true or false.
The simple operations we carry out on Boolean values, when combined in clever ways, let a computer do all the clever things it's able to do. When you move your mouse pointer, there's a whole cascade of little ones and zeroes bouncing around inside the chips and cables that you will never see.
In the context of JavaScript, Booleans are useful in decision making. Should we do this or that? Should we let the user submit their shopping cart or not. Should this element be clickable or not. Lets have a look at what we can do.
One of the simplest things we can do with Booleans is the "and" operation. It looks like this:
var daytime = true;
var sunny = true;
var canGoOut = (daytime && sunny);
Here we set a variable called canGoOut. This variable will be true if both daytime and sunny are true.
We can use this in a program like so:
var daytime = true
var sunny = true
var canGoOut = (daytime && sunny);
if (canGoOut) {
alert("lets go out!")
}
or more simply
var daytime = true
var sunny = true
if (daytime && sunny) {
alert("lets go out!")
}
Questions
The second useful thing we can do with Booleans is or. Sometimes we want to be able to say "do something if this other thing is true, or if this second other thing is true. We say or in Javascript using the vertical bar character. For example:
var iFancyIcecream = false;
var youFancyIcecream = true;
var buyIcecream = (iFancyIcecream || youFancyIcecream);
We can use this in a program like this:
var iFancyIcecream = false;
var youFancyIcecream = true;
if (iFancyIcecream || youFancyIcecream) {
alert("I am just going to the shop now...");
}
Questions
The last useful thing we can do with Booleans is Not. Sometimes we want something to happen if something is not true. For example we might want to display an error if someone has not filled in a field correctly. We say not! in JavaScript using an exclamation mark, like so:
var filledInField = false
if (!filledInField) {
alert("Please fill in the field!");
}
Questions
So far and so esoteric. It's all very well setting Boolean values explicitly in our code, but for this to be useful we need to be able to be able to make Booleans from other values. Lets return to our timing example above. Lets say that have a variable called hour, and we want to determine if it's mid-day or not. We might do something like this:
var hour = 12;
var midday = (hour === 12);
alert(midday);
Here we're simply saying: if the hour variable is equal to 12, the midday variable is true. In JavaScript === means equal to.
Questions
We can do other mathematical operations to make Booleans. Here we do one thing if hour > 12 and another if hour is less than 12.
var hour = 13;
if (hour > 12) {
alert("after midday");
} else {
alert("before midday");
}
We can combine Boolean operators too, for example:
var hour = 13;
if ((hour > 11) && (hour < 14)) {
alert("you could have lunch now.");
} else {
alert("it isn't lunchtime.");
}
Questions
var hour = (new Date()).getHours();
Hook your clock up to the actual hour of the day.
More Questions
The best way to tackle this is with an if / else if / else statement. There are 3 possible results, either one dad is bigger than the other, or they are the same.
var myDadSize = 12;
var yourDadSize = 13;
if ( myDadSize > yourDadSize ) {
alert("My dad is the biggest (of course).");
} else if ( myDadSize < yourDadSize ) {
alert("Oh, your dad is the biggest.");
} else{
alert("Our dads are the same size");
}
So, we've learned most of the major things we need to know in order to program. We're nearly ready to create some cool stuff. There are just one more thing we need to know before we jump into section two. Loops.
Remember Mrs. Potts and the poor starving children? I wonder what happened with that. Do you think the children were OK? I hope so. We helped Mrs. Potts a lot by giving her a makeSandwich function, but she still needs to call it a lot of times. What if there was an easy way for her to call the makeSandwich function 10 times, 100 times, a million times without writing one more line of code.
Thankfully there is! Enter Loops!
A while loop in JavaScript is a type of loop that will keep going while some condition is true. For example
var sandwichesMade = 0;
while (sandwichesMade < 5) {
alert("Making Sandwich: " + sandwichesMade);
sandwichesMade = sandwichesMade + 1;
}
First we set the number of sandwiches we have made so far:
var sandwichesMade = 0;
Then we say to the Javascript engine
while (sandwichesMade < 5) {
//do something
}
This is the loop. It will go round until the condition sandwichesMade < 5 is not true any more.
Inside the loop we have to remember to do this:
sandwichesMade = sandwichesMade + 1;
This increases the value of sandwichesMade. Without this, the loop will go around forever until the page times out.
Questions
More Questions
Even More Questions
The other type of loop we need to know is the for loop. This type of loop is similar to the while loop, but we roll all the various different parts of it up into one line, like so:
for (var sandwichesMade = 0; sandwichesMade < 5; sandwichesMade++) {
alert("Making Sandwich: " + sandwichesMade);
}
This loop says. sandwichesMade starts at 0, the loop continues until sandwichesMade < 5, and at the end of each loop increase sandwichesMade by one.
sandwichesMade++
is just shorthand for add one to the sandwichesMade variable.
Questions
Answers
To tackle this problem, we need a variable to store the current countdown. Here I have called it number. While number is > 0, we loop, reducing the value of number. When number drops below zero, the loop exits and the lift off line is run.
note that number– decrements the value of number by one.
var number = 10;
while (number > 0) {
alert(number);
number--;
}
alert("Lift off Mrs Potts");
More Answers
This code is similar to the above, except we have wrapped it up in a function.
var countdown = function(number) {
while (number > 0) {
alert(number);
number--;
}
}
coundown(10);
Even More Answers
We can make an infinite loop using a while loop. We simply say while(true). True is always true by definition.
var number = 0;
while (true) {
alert(number);
number++;
}
Mrs Potts is in trouble. She has been given the job of making Pizza's for the staff room Pizza Party. The head wants cheese and tomato, but the deputy head wants 5 cheese, pepperoni, mushroom and ham. How can she represent all these ingredients in a JavaScript friendly fashion? It's keeping her awake at night.
Thankfully, we can rescue Mrs Potts using Arrays. If a variable is like a bucket, an array is like a rack of buckets, each with a label on it. We can add as many buckets to the rack as we like, and we can put any labels we like on the buckets.
The simplest way to make an array is to declare it, like so:
var toppings = [ ];
We use square brackets to define an array. This is an empty array.
If we like we can put some things in it:
var toppings = ["ham", "cheese", "parmesan"]
We now have an array containing 3 ingredients. It's a rack of 3 buckets.
Because we haven't declared any bucket names, Javascript has done it for us by giving each bucket a number. This is subtly different to other languages, do take note.
Let's take pull out a bucket:
var toppings = ["ham", "cheese", "parmesan"]
alert( toppings[1] );
This will alert the string "cheese". If we want "ham", we need the zeroth bucket, like so:
alert( toppings[0] );
What if we want to store something at a particular point. Let's do this now:
var toppings = ["ham", "cheese", "parmesan"];
toppings[3] = "little tiny cherry tomatoes";
Here we have put another value in toppings, this time in bucket number 3.
We can verify that our array is now longer using toppings.length. The dot operator is to do with object orientation, which we will cover later.
alert(toppings.length)
…will output the number 4.
JavaScript arrays are different to arrays in most languages. In most languages, array elements are pointed to by a number. In JavaScript, you are free to use a number to point to an element in an array, but you can equally use a string.
Arrays in JavaScript are actually same the datatype that many other languages call a hash table.
One of the most common things you will want to do with an array is to do something with each of it's values. We can use a for loop for this.
var toppings = ["ham", "cheese", "parmesan"];
for (i = 0; i < toppings.length; i++) {
alert(toppings[i]);
}
Here we loop over each numbered bucket and output it's value. Note that this only works with sequentially ordered buckets. This is the most efficient way to iterate over an array.
The other common way to iterate over an array is using a for in loop, like so:
for (var i in toppings) {
alert(toppings[i]);
}
This works if our arrays are not sequential, so for example:
var toppings = [];
toppings[10] = "ham";
toppings[45] = "cheese";
toppings["happy kittens"] = "parmesan";
for (var i in toppings) {
alert(toppings[i]);
}
That's all very well and good, but what about poor Mrs Potts? Let's write some code that will let her make pizzas with any number of toppings.
Let's make pizza.
You should have correctly identified that we needed a loop. Here I am using a for loop. I've added a little extra code to add ampersands between the toppings.
var make_pizza = function(toppings) {
var pizza = ""
for (i = 0; i < toppings.length; i++) {
pizza = pizza + toppings[i] + " ";
if (i < toppings.length - 1) {
pizza += "& ";
}
}
pizza += "pizza";
return pizza;
}
alert( make_pizza( ["ham", "cheese", "parmesan"] ) );
Here is an array of requests:
var filling_requests = ['ham', 'cheese and cucumber', 'humous and mayo'];
['ham sandwich', 'cheese and cucumber sandwich', 'humous and mayo sandwich'];
You've made it, now lets make it fly…
For the most part, when we write JavaScript, we want to use it to talk to and affect web pages. We do this via a thing called the Document Object Model or DOM - a series of JavaScript objects that let us interact with every part of the page.
Unfortunately the DOM was put together in a bit of a hurry and is not very easy to use. Douglas Crockford described the DOM as "The worst API ever conceived of". For this reason we tend to use a Javascript wrapper to make talking to the DOM easier.
There are lots of libraries available that help us interact with the DOM such as MooTools, Prototype and Closure. In this course we'll be using a library called JQuery.
If you're interested, we can look at so called DOM scripting later in the course. DOM scripting lets us talk to the DOM directly. It's slow, fiddly, and works differently in different browsers, but it's still good to know about.
So lets jump right in! First we need to download a copy of jQuery, so go visit jquery.com and download the latest version. I've got version 1.8 here in front of me now, but you'll probably get a newer version that this. You'll be offered the choice between a regular or minified version. Choose the regular version for now.
Now we need to create an html file for our scripts to live inside. Enter something like the following:
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="jquery.js"></script>
<script src="hello.js"></script>
</head>
<body>
</body>
</html>
Note that the body element is empty.
Next we'll need to create the hello.js file, so go ahead and create it and add the following text:
$(function() {
$("body").html("Hello jQuery");
});
Whoah, that looked complicated! Don't worry though, there's actually nothing here that we haven't already covered in part 1. We'll break this down in a minute, but for now let's just type it in and have a look.
Questions
The code we entered just now might look strange, but actually it's quite simple. JQuery works by defining a single function called $. Why $? Because $ easy to type and has no meaning in JavaScript. Here is our Hello jQuery script again.
$(function() {
$("body").html("Hello jQuery");
});
Notice that it is wrapped in the dollar function like this:
$( ...code goes here... );
Now it makes more sense, we have a function called $ (dollar) which accepts an argument. Remember in the last section we looked at functions, we said that a function could be assigned to a variable? That's because, in Javascript functions are "objects". We can pass them around, do things with them, assign them to variables, etc, etc.
In this case the dollar function is accepting another function as an argument. The function it's accepting looks like this:
function() {
$("body").html("Hello jQuery");
}
This is an anonymous function, it doesn't have a name, but it's a function none the less. Lets look inside it:
$("body").html("Hello jQuery");
This looks simpler. We're calling the $ function again, but this time we're passing it a string "body". When the $ function receives a string, it uses it to find an element on the page. Horray, it has found the body element!
JQuery adds a bunch of convenience methods to any element it returns including this one .html(). The html method lets us set the html content of an element, so here we've set the content to the string "Hello jQuery".
Passing $ a function
One mystery remains, why did we have to pass our code to $ as a function? Why wrap all that stuff up inside a function at all?
Well…
The dollar function behaves differently depending on what you pass it. If you pass it a string it finds the element that matches that string. If you pass it a function, it remembers that function and calls it as soon as the DOM is ready, that is, as soon as your page has downloaded. So by wrapping our code up in a function and passing it to jQuery first thing, we guarantee that jQuery won't try to run our code until our HTML is ready.
Let's look at it another way…
You: Hi jQuery, I've written some code. Here's a function for you. I'll pass it to you using your $ function. I know you like that..
jQuery: Thanks User, I'll execute that function just as soon as the page html has finished loading and the DOM is ready. I'm clever and I know just when that will be for all the various different browsers.
…time passes…
jQuery: Ah, the DOM is ready, lets look at that function. Little Function? You can run now!
Little Function: Hello there jQuery, nice to be running at last. jQuery, can you find me the body element?
jQuery: Of course I can, with pleasure! Here it is, and I've taken the liberty of decorating it with a bunch of useful utility methods for you.
Little Function: Great, I'll call the html method to set the html of the body element you gave me on the DOM.
DOM: Aha, oho, you've set the inner html of the body element. I'll just tell the browser.
Browser: Thanks DOM. What's that you say? You've been updated? I'd better redraw myself. There, that's all done.
… more time passes…
You: Horray. My page now contains the text I wanted!
In the example above, we used jQuery to set the html of the body element. We selected the body element, then called the html method on it.
We can use jQuery to select any element on the page. We do this using CSS syntax. Lets say we wanted to select all the paragraphs on the page, we would do this like so:
$("p");
Lets say we wanted the hyperlink with class name "login":
$("a.login");
The string is just CSS.
Questions
Because jQuery uses CSS to select elements, plus it's own extensions, you can use jQuery to pull out and make changes to pretty much anything on the page. It works in all browsers so you don't need to worry about browser inconsistencies.
Read http://api.jquery.com/category/selectors for a full up to date list of selectors. It's a long and useful list.
The real strength of JavaScript is that it allows the page to respond to the user. Whenever the user does something on the page, from moving the mouse to pressing a button, to submitting a form, lots of little events are fired off in the browser. We can tell our code to listen for certain events and call functions in response to them.
Questions
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="jquery-1.5.js"></script>
<script src="dont_click.js"></script>
</head>
<body>
<div class="clickable">
Do not press this button.
</div>
</body>
</html>
$(function() {
$(".clickable").click(function() {
alert("I can't believe you just did that!");
});
});
Deconstructing don't click
How was that? Tricky? Make sense? Let's just deconstruct the JavaScript a little and have a look inside.
First we have this
$(function() {
...
});
This calls the dollar function and passes it a function. When we pass dollar a function, jQuery puts it on one side until the DOM is loaded and runs it then. jQuery
The function we passed it looks like this:
$(".clickable").click(function() {
...
});
Can you guess what it does? First it gets all the elements on the page with class "clickable". Then it calls a method called click on them. This method says what to do when we click. It's a click handler.
And what happens when we click it? This happens:
alert("I can't believe you just did that!");
…and we get our cute little alert box. So appealing!
More Questions
OK, it's not sexy, but sooner or later we're going to have to cover it. Forms. There, I've said it. Don't worry, next well be looking at animation so lets just take a deep breath and…
Make a form:
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="jquery-1.5.js"></script>
<script src="form.js"></script>
</head>
<body>
<form>
<label for="gadget">Please enter a handy gadget, eg jet boots.</label>
<input type="text" id="gadget" />
<input type="submit" value="Go Go Gadget jQuery!">
</form>
</body>
</html>
This simple form doesn't do much. Let's make something happen with some…
Go Go Gadget JavaScript!
$(function() {
$("form").submit(function() {
var gadget = $("#gadget").val();
alert("Go Go Gadget " + gadget);
return false;
})
});
As you'd expect, jQuery lets us look at the values of form elements. It does this using the val method on any form element. As you can see above, we're responding to the submit event with a function that writes an alert to the screen.
Questions
We can do lots of things with forms.
More Questions
As promised, here we are in the animation section, and what a section it is! jQuery provides a rich and detailed animation library. There are lots of built in effects, or we can define our own, transitioning between pretty much any CSS property you care to mention.
Lets look at some examples
Before we get stuck in, lets look at some examples.
First of all, let's look at some examples, so head on over to:
http://jqueryui.com/demos/effect/ http://api.jquery.com/category/effects/
…and have a look at some of the demos there. They should give you an idea of what can be done.
I'm a Ninja, watch me fade
For this example we're going to look at the fadeIn effect. This is a nice effect for revealing things in a smooth way.
The HTML
There's a fair amount of inline CSS here. If you want to do this properly do please extract this into a separate CSS file, I'm just doing it this way for brevity and clarity.
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="jquery-1.5.js"></script>
<script src="fade_in.js"></script>
</head>
<body>
<div class="hi" style="display:none; width:200px; height:200px; background:red;">Hi There, I'm a ninja.</div>
</body>
</html>
The Javascript
$(function() {
$(".hi").fadeIn(1000);
});
As you can see, when the DOM is ready the hi div is faded in.
Questions
There's lots more we can do with Javascript. We can get and set attributes using the attr method. We can add and remove classes using the addClass and removeClass methods. We can set CSS styling using the css method. It all fits inside the same basic framework and I encourage you to try things out.
Well that just about wraps it up for this little book. I hope you've enjoyed it, and that you now have a pretty sound footing in JavaScript.
IF you;d like to continue your JavaScript journey, the next thing to look at is JQuery. My little book of JQuery will be available soon.