A function is a bit of code that takes some input and produces some output. You can get really complicated with functions, but at heart, that's all they are.
Functions are the best, because they let you turn computers into your personal army of robot servants.
Photo by legoalbert – http://flic.kr/p/evHiGW – CC BY
How? Because you write your function once, and then the computer can execute it wherever and whenever you need, as often as needed -- even millions of times in a row. And unlike humans, your robot servants are blindingly fast and perfectly accurate.
Bonus: you can debug your function once, and it works everywhere. Yay!
Let's have a look.
Remember this?
$j("#yellow-div").addClass('bg-purple').removeClass('bg-yellow');
We're going to make it fancier. But first, let's refresh our memory. Arguments are the inputs to a function (highlighted in purple above). Arguments give a function information about what it should be doing and how to do it. What are these arguments telling this function?
Some functions require arguments; some don't. A function may take 1 or 2 or many arguments. It may have optional arguments. When you write your own functions from scratch, you can decide what arguments they take, based on what makes sense for the function you're writing.
Typically each argument must be of a certain data type. Again, when you write the function, you can define that however you want. You just have to stick to it once it's defined.
Now, let's make it fancier!
$j("#yellow-trigger").on("click", function() {
$j("#yellow-div").addClass('bg-purple').removeClass('bg-yellow');
});
What have we here?
The inner line we've seen before. What do you expect it to do?
The rest of the code tells us when and how to trigger the inner line.
$j("#yellow-trigger")
tells us what element
to bind our function to. (Binding means that
this element can trigger the function, and other elements
can't.)
.on(...);
is a jQuery function that attaches
an event handler to an element. An event handler
is, quite literally, a function that tells your browser how
to handle particular events — what to do when
specific things happen. The event you'll see handled most often
is click
; we'll be telling the browser what to
do when people click on things. Other JavaScript events
include mouseenter
, mouseleave
,
submit
, keypress
...various ways
people can interact with browser content. You can read more
in the jQuery
documentation on event handling.
Back to .on()
! It takes two arguments:
"click"
. There are
many other event
types.
function() {...}
.
And what's all that punctuation doing in the third line? That's
the closing } for function() {...}
and the closing
); for .on(...);
.
Try it!
If you get stuck, talk to your neighbors and check out the Troubleshooting section at the bottom of the page.
#purple-div
) in the box below change color when you
click on the purple-trigger button (#purple-trigger
).
.lavender-div
) in the box below change color when
you click on the lavender-trigger button
(#lavender-trigger
).
Sometimes you want to exercise some judgment, you know?
If you can write a clear enough rule, you can tell your robot servant to make choices for you.
In your own words, what does this rule say?
$j("#conditional-trigger").on("click", function () {
if ( $j("#conditional-button-1").html().indexOf("Purple me!") >= 0 ) {
$j("#conditional-button-1").removeClass('bg-green').addClass('bg-purple');
} else {
$j("#conditional-button-2").removeClass('bg-green').addClass('bg-purple');
}
});
Once you have your guess and not before, click the conditional trigger:
By the way, did you find that function hard to read? I did. We can make it easier to read by splitting up the steps a bit and using a thoughtfully named variable, thusly:
$j("#conditional-trigger").on("click", function () {
var shouldIPurpleIt = $j("#conditional-button-1").html().indexOf("Purple me!");
if ( shouldIPurpleIt >= 0 ) {
$j("#conditional-button-1").removeClass('bg-green').addClass('bg-purple');
} else {
$j("#conditional-button-2").removeClass('bg-green').addClass('bg-purple');
}
});
As always, decide what you think should happen
before you write any code. And don't forget to type in
var $j = jQuery.noConflict();
first, just in
case. (You only need to do this the first time you load the
page.)
bg-orange
and bg-purple
are the class names that govern background colors in my
stylesheet.)
Using functions in loops is where the real power of programming kicks in. After all, there are lots of tasks you can do once just as quickly and accurately as a computer can (and generally faster than you could write the code!) But there aren't many things you can do ten thousand times as quickly and accurately as a computer.
So now let's do something a whole lot of times. What will the following code do?
$j("#loop-trigger-1").on("click", function() {
$j(".loop-1").each(function() {
$j(this).removeClass('bg-yellow').addClass('bg-purple');
});
});
Or...let's try something more useful. What will this do?
var resultsDiv = $j("#results-div");
$j("#loop-trigger-2").on("click", function() {
$j(".record-set").each(function() {
var titleList = $j(this).html().split(":");
var titleName = titleList[1];
resultsDiv.append(titleName + '<br />');
});
});
Imagine this idea with a much larger data set - a spreadsheet or a batch of MARC records. What sorts of things could you do?
Let's put together everything we've learned: functions, loops, and conditionals. In other words, let's have super-fast, hardworking robots make judgment calls about All The Things.
What will this code do?
$j("#loop-conditional-trigger").on("click", function() {
$j(".loop-2").each(function() {
var targetColor = $j(this).html();
if ( targetColor.indexOf('Purple') >= 0 ) {
$j(this).removeClass('bg-yellow').addClass('bg-purple');
} else if ( targetColor.indexOf('Orange') >= 0 ) {
$j(this).removeClass('bg-yellow').addClass('bg-orange');
} else if ( targetColor.indexOf('Lavender') >= 0 ) {
$j(this).removeClass('bg-yellow').addClass('bg-lavender');
}
});
});
.append()
? We used an
example on the loops page.)
Please fill out the feedback survey.
Because we're human, we usually don't think of all the edge cases the first time we write programs, and we do often make mistakes. As we discover omissions and errors over time, we make our programs better. This is as true for people in their first day of programming as it is for people in their twentieth year -- you just get to make more interesting mistakes with experience, and develop more sophisticated tools for fixing them.
This means that being a good programmer isn't about never making mistakes. We all make mistakes. It's about persevering until you fix them. Take a break and come back if you need to, by all means ask for help. do whatever works to manage your frustration levels, but stick with it, and you'll end up a good programmer.
A lot of the challenge, fun, and frustration of programming is figuring out how to write clear enough rules. If a program doing something, but not what you expect, check your logic:
If the program isn't doing anything, or you think your logic is right but you're still not getting the behavior you expect, check your syntax:
Uncaught SyntaxError: Unexpected token (
or
similar: did you close all your open parentheses? Did you
spell your function names right? Look at all
your parentheses to make sure they're right; then look
near them for errors. Sometimes the SyntaxError
the computer raises refers to something just after the
mistake you actually made, because the computer keeps
going until it realizes it doesn't know what's going on
before it complains (much like some people you probably
know...).
"Uncaught ReferenceError: X is not defined"
:
make sure you actually defined it! Check that its
spelling and case are consistent.
Some helpful techniques:
alert(X);
or console.log(X);
statements into your code. X should be a variable whose
value you want to check. This will make the computer tell
you what it thinks X is at a given point in the
program; you can compare that against what you expect X to
be.