Lesson Monday

Important Note: jQuery is updated constantly! Faster than we can reasonably update this lesson! As such, make sure your <script> tag links to the specific version and filename your project is using (e.g. src="js/jquery-1.12.4.js" instead of src="js/jquery-1.10.2.js"). The versions depicted in the <script> tags in this lesson likely won't match the version in your project.


Also, the video used the shortcut of abbreviating $(document).ready() to $(). We've since updated this lesson's text to use the first, more explicit version after observing confusion from students. Know that these things are the same, and one is simply a shortcut for the other.

Important Note: jQuery is updated constantly! Faster than we can reasonably update this lesson! As such, make sure your <script> tag links to the specific version and filename your project is using (e.g. src="js/jquery-1.12.4.js" instead of src="js/jquery-1.10.2.js"). The versions depicted in the <script> tags in this lesson likely won't match the version in your project.


Also, the video used the shortcut of abbreviating $(document).ready() to $(). We've since updated this lesson's text to use the first, more explicit version after observing confusion from students. Know that these things are the same, and one is simply a shortcut for the other.

Now that we know a bit of JavaScript, let's learn jQuery, a JavaScript library that makes it easy to make web pages interactive. Let's start by learning how to pop up dialogue boxes when you click certain parts of the page.

Setup a new project. (Make a project folder, create js, css and img folders inside of it, and initialize the git repository.)

First, we need to add two files into our project's js folder - the jQuery library file and our custom scripts file. Go ahead and download jQuery. Choose the uncompressed, development version and save it into your project's js folder. Then, also inside your project's js folder, make an empty file called scripts.js to store our own JavaScript code. Then begin developing our page with this HTML in a file in our project directory:

html-help.html
<!DOCTYPE html>
<html>
  <head>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <title>HTML help</title>
  </head>
  <body>
    <div class="container">
      <h1>HTML help</h1>

      <p>This is a very special page. If you click somewhere, it will tell you what type of HTML element you clicked on.</p>

      <p>Look at this cute walrus!</p>
      <img src="img/walrus.jpg">
    </div>

    <script src="js/jquery-1.9.1.js"></script>
    <script src="js/scripts.js"></script>
  </body>
</html>

It's important that our own scripts.js file goes after jQuery, as it will rely on jQuery functionality that must be loaded first. Make sure your link to the jQuery file is correct, with the version number matching what you downloaded.

Okay, we're finally ready to use jQuery! Here's the code to type in scripts.js:

js/scripts.js
jQuery("h1").click(function() {
  alert("This is a header.");
});

jQuery("p").click(function() {
  alert("This is a paragraph.");
});

jQuery("img").click(function() {
  alert("This is an image.");
});

Be sure you're indenting correctly! The alert()s are two spaces in, because they're inside the function()s.

If we load up the page and click on different parts, we'll get dialog boxes popping up and telling us what they are. Hooray! Now, let's look more closely at how this works.

Here we have a new function: the jQuery() function! One thing that the jQuery function does is to select HTML elements on the page, based on the argument you pass in to it. So the code jQuery("p") selects all of the paragraphs on the page.

After we select the elements, we use jQuery's .click() method to attach an event handler to each of the selected elements. The event handler "listens" to the elements and responds when they're clicked.

Next, we need to tell jQuery what to do when the user clicks that element. We pass in a function as an argument. The function() we're using here is just like the ones we practiced before, but we aren't assigning it to a variable and we're passing it as an argument to another function. This is called an anonymous callback function. It is a callback function because it is not executed immediately; instead the function is passed in to the jQuery click() function to be executed at a future time - in the case of the .click() function, when that event handler is triggered by a user clicking on any of the selected elements.

Inside the callback function, we can put whatever code we want, just like in the functions we wrote before. Here we call the alert() function to pop up a dialog box with some helpful information. We could actually pop up two alerts, like this:

jQuery("h1").click(function() {
  alert("This is a header.");
  alert("I told you, THIS IS A HEADER!");
});

To reiterate, when you pass in a function as an argument to another function, the function being passed in is called a callback.

Phew! That's a lot of work just to make a few silly pop-ups. Fortunately, even though this might feel a bit overwhelming at first, most of the jQuery we'll write will look an awful lot like this, so you'll get the hang of it pretty quickly.

Let's do a couple things to clean up our code. First, it feels a bit wrong to put our <script> tags in the document body, where the content of the page lives. Let's move them up into the <head>, which is where we put information about the page that isn't displayed:

html-help.html
<head>
  <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
  <script src="js/jquery-1.9.1.js"></script>
  <script src="js/scripts.js"></script>
  <title>HTML help</title>
</head>

Oh dear. Now, if we reload the page in our browser, nothing happens when we click anything. Let's review our JavaScript to see why this broke it. Remember that I said that jQuery('p') will look for all of the <p> tags on the page? The web browser loads your page from the top of your HTML document to the bottom. So when we put our JavaScript in the <head>, rather than at the end of the document, there are no <p> tags yet, and so there's nothing for .click() to attach to. What we need to do is tell our JavaScript not to run until the document has finished loading. Fortunately, jQuery provides an easy way to do this:

js/scripts.js
jQuery(document).ready(function() {
  jQuery("h1").click(function() {
    alert("This is a header.");
  });

  jQuery("p").click(function() {
    alert("This is a paragraph.");
  });

  jQuery("img").click(function() {
    alert("This is an image.");
  });
});

Here, we tell jQuery to look at the HTML document, and then we call the .ready() method on it. When the document has finished loading, jQuery will run the callback function that is passed into .ready(). And that function will run our code. Generally, it's a good idea to wrap your JavaScript in a function passed to .ready(), so that it's executed after the page loads and you don't run into the problem we just had.

Check out our page - it works again.

There's a handy shortcut that most JavaScript developers use: instead of writing jQuery() all of the time, we can simply use $():

js/scripts.js
$(document).ready(function() {
  $("h1").click(function() {
    alert("This is a header.");
  });

  $("p").click(function() {
    alert("This is a paragraph.");
  });

  $("img").click(function() {
    alert("This is an image.");
  });
});

This isn't really necessary, but it saves us a little bit of repetitive typing, and is how most people write the jQuery function.

Here's one final trick I want to show you. If something on your page isn't working right, you can check in Chrome to make sure that you've attached the event listener correctly. Right-click the element you want to check, go to Inspect Element, and then, in the upper right corner of the box on the bottom, click Event Listeners. If you've attached the listener correctly, you should see it listed there.

Terminology


  • Event handler: an event handler "listens" to the element(s) to which it's attached and responds when a certain event is triggered. .click() is a click listener, which is a type of event handler that responds when an element to which it's attached is clicked.

  • Callback: a function passed as an argument to another function. A callback function is not executed immediately; One use of callback functions is that they are passed into event handlers to be executed at a future time.

Resources


Examples


Link jQuery before your scripts that use it:

<head>
  <script src="js/jquery-1.9.1.js"></script>
  <script src="js/scripts.js"></script>
</head>

Select a tag and bind an event handler to it:

$("h1").click(function() {
  alert("This is a header.");
});

The part function() { alert("This is a header."); } is considered the callback because it is being passed as an argument into the method .click().

Wrap all your jQuery code in callback passed to $(document).ready() so that it is run after the page loads:

$(document).ready(function() {
  $("h1").click(function() {
    alert("This is a header.");
  });
});

To check if an event handler is attached properly, right-click the element you want to check, Inspect, and click Event Listeners.