Introduction to Programming Concepts via jQuery

Functions!

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.

An example function

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.

If you're calling a function and it isn't working, proofread to make sure you've supplied the correct number of arguments, in the correct order, of the correct type. Good documentation will always (not just in jQuery!) tell you what arguments a function can take.

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:

  • The event: here, "click". There are many other event types.
  • The function that should be called to handle the event. Here, we're writing our own, as signified by function() {...}.
Yes, the quote marks around the event type matter.

And what's all that punctuation doing in the third line? That's the closing } for function() {...} and the closing ); for .on(...);.

Yes, the punctuation matters. If something isn't working, put on your best cataloger hat and proofread. Anything opened must be closed!

Try it!

Your turn

If you get stuck, talk to your neighbors and check out the Troubleshooting section at the bottom of the page.

  1. Write a function that makes the purple div (#purple-div) in the box below change color when you click on the purple-trigger button (#purple-trigger).
  2. Write a function that makes all the lavender divs (.lavender-div) in the box below change color when you click on the lavender-trigger button (#lavender-trigger).

More intelligent robots: functions + if/then

Sometimes you want to exercise some judgment, you know?

  • Mark the book for weeding if (but only if) it hasn't circed in a decade
  • Add an 856 $u if (but only if) you have a URL for the record
  • Display a libguide on a course page if (but only if) you have a relevant one

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');
    }
  });

Your turn

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.)

  1. Write a function that makes the trigger-1-target div turn orange, if it contains the word "orange", when you click trigger-1.
  2. Write a function that makes the trigger-2-target div turn orange if it's currently purple when you click trigger-2. (Remember bg-orange and bg-purple are the class names that govern background colors in my stylesheet.)
  3. Write a function that makes the trigger-3-target div turn orange if it's green when you click trigger-3.
If you're stuck, test smaller components of your function and see if they work.
  • Can you define a variable like shouldIOrangeIt without throwing any errors?
  • What happens if you write just the if condition for shouldIOrangeIt - does that turn out true or false (and is that what you expected)?
  • Can you write a line that changes the color of your target (without doing an if condition or binding to a click event on anything)?
Testing each line in isolation is much easier than testing the whole thing at once.

More industrious robots: loops

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 />');
    });
  });


Results

Imagine this idea with a much larger data set - a spreadsheet or a batch of MARC records. What sorts of things could you do?

Your very own robot army

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');
        }
    });
  });

Your turn!

  1. Write a function that, when you click on #trigger-4, looks at all the .trigger-4 buttons and, if they're green, turns them purple.
  2. Write a function that, when you click on #trigger-5, looks at all the .trigger-5 buttons and, if they're green, appends their contents to the #trigger-5-results-div. (Need a refresher on .append()? We used an example on the loops page.)
  3. Write a function that, when you click on #trigger-6, loops through the .trigger-6 buttons and produces results that match the #trigger-6-results-div contents. (Step 1: figure out what rule(s) you need to follow to do this!)

Desired results


Your results

Desired results

Zoia Horn
Melvil Dewey
Charles Ammi Cutter
Judith Krug

Your results

Desired results

Zoia Horn
Melvil Dewey
Callimachus
Henriette Avram
Suzanne Briet
Charles Ammi Cutter
Judith Krug

NERCOMP feedback

Please fill out the feedback survey.

Troubleshooting!

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.

Fixing logic errors

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:

  • Does your rule actually apply to all the cases it needs to?
  • Does your rule accidentally apply places it shouldn't?
  • Does your rule have exceptions you need to account for?

Fixing syntax errors

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:

  • Did you end all your lines with semicolons?
  • Do the ID/class names you're using in your function match the ones on your HTML element(s)?
  • JavaScript is case sensitive; variablename and variableName are different. removeClass() is a function, but removeclass() is not. Have you been consistent in your case usage?
  • 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.

Techniques

Some helpful techniques:

  • Type your function into the console a little at a time. Try just the selector that you're binding your function to - is it grabbing the right piece of HTML? Try leaving out the on("click") outer shell and just writing a line in the middle of the function - does it make the change you expect? If you're trying to write a loop, can you first write a line of code that changes one thing? Once you've got individual components that work, sewing them together will be simpler.
  • If it's hard to read your function in the console (especially as it gets longer), edit it in a text editor where you can space it out and use a bigger font. When you're satisfied, copy-paste it into the console window.
  • Add 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.
previous next