Lesson Tuesday

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

Introduction to jQuery


jQuery is a JavaScript library that makes it easier to incorporate JavaScript on your web pages. When we say it is a library, we mean that many common tasks that would take many, many lines of JavaScript code to execute have been packaged into methods that you'll be able to use with a single line of code. These methods are always available and ready to use the same way you might check out a book at a library. The goal of libraries is to allow its users to "write less, and do more".

The goal of using jQuery in our projects is to enable us to easily add interactivity. Making a webpage interactive means writing code that can react to user input and other events, like a button click or a form submission. Instead of using JavaScript directly to add interactivity to our webpages, we'll use the JavaScript library called jQuery.

Documentation for jQuery

Just like JavaScript has online documentation on MDN (among other locations), jQuery has an official site with its own detailed documentation on all of the methods and tools that are available when you use the jQuery library.

The documentation we're interested in is the jQuery API located at https://api.jquery.com/. If you follow that link, it will take you to a homepage with all of the methods listed available for use (you'll need to scroll down on the page). We'll only be working with a select few methods, which we'll detail how to use in upcoming lessons. The jQuery documentation can be a bit challenging to understand as newcomers, so know that all of the jQuery that you'll need for this section's independent project will be covered in this section's material. The documentation is simply there to support you if you want to explore further and try out new methods.

What is an API?

Note, the API in "jQuery API" stands for application programming interface. An API is a set of code (like methods) that let's us interact with more complex software (like a library) in a pre-defined way.

We use interfaces all of the time. Consider a door knob - the knob is the interface that we interact with that handles abstracting the complex internal hardware of the door latch. When we use the door knob, we're triggering the door hardware to do its thing to open the door latch. We don't need to concern ourselves with how the door latch works, we just need to know how to use the door knob. Similarly with jQuery, we don't need to know or understand exactly how the jQuery library is set up, we just need to learn how to use its API. "API" specifically means that the interface we're working with is for programming applications, and the API does the job of letting our program (that we create) talk to another program (the jQuery library).

You may be thinking "I thought jQuery is a JavaScript library not an API." Well, you are correct. jQuery is a library - a set of code that we can call on to use in our programs. However, jQuery also includes an API (actually, a couple APIs) to let us "talk to" their library. If the distinction between library and API is not clear, it's not something to worry about. This information is for context-building only and you won't be tested on it. We'll revisit this information, and later in the program, we'll work more with APIs and even create our own!

Project Setup


We'll learn about jQuery by building a new project.

Setup a new project:

  • Make a project folder.
  • Create js, css and img folders inside of it.
  • Initialize the git repository.

Next, we need to add two files into our project's js folder - the jQuery library file and our custom scripts file.

Download jQuery and Create scripts.js

Go ahead and download jQuery. Choose the uncompressed, development version and save it into your project's js folder. For this and other projects, we'll be using jQuery version 3.5.1. It's fine if you use a different version - just make sure that you link to the correct name!

Note that when you click on the uncompressed development link it may take you to a page with the raw JavaScript instead of downloading automatically. This is fine. If you are using Chrome, go to File > Save Page As in the dropdown menu. The format of the file should automatically be JavaScript and the name should already be complete. Click the "Save" button and the file will be saved in your Downloads folder. (If you've specified another directory for downloads, it will be saved there instead.) Move this file in your project directory's js folder.

Next, also inside your project's js folder, make an empty file called scripts.js to store our own JavaScript code.

Then, let's begin developing our website by adding this HTML in a file called html-help.html in our project directory:

html-help.html
<!DOCTYPE html>
<html lang="en-US">
<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-3.5.1.js"></script>
  <script src="js/scripts.js"></script>
</body>
</html>

Placement of the jQuery <script> Tag

It's important that our own scripts.js file goes after the jQuery <script> tag, 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.

Also, if you are wondering why we've placed our <script> tags at the bottom of our HTML body - we will get to that soon.

Before we continue on to using jQuery, let's review another way to download jQuery into our projects.

Optionally, Use a CDN to Load jQuery into Your Project

We briefly covered CDNs in the last section when we introduced using a CDN with Bootstrap as one way to load Bootstrap files into your project. Let's review now.

A content delivery network (CDN) is exactly what it sounds like - a network of servers that make content available for users. In this case, jQuery is making its JavaScript library available online, which means we can just load the online version directly to our project without needing to add any files to our js directory.

Finding jQuery's CDN Script

You can use the most up-to-date version of jQuery in your projects, however we'll use version 3.5.1 in our walkthroughs. There's a couple of ways to get the script tag for jQuery's CDN.

First, you can learn about jQuery's CDN by navigating to the section titled 'Using jQuery with a CDN' on the jQuery Download webpage. In that section, you'll find a host of information and links to a CDN releases page at https://code.jquery.com.

You can also navigate directly to the releases page, by going here: https://releases.jquery.com/.

From the jQuery CDN releases page, we can select any option under jQuery Core. For each stable version, we can select 'uncompressed', 'minified', 'slim', or 'slim minified'. We won't select either 'slim' option, because this excludes some methods in the jQuery library. For our purposes either uncompressed or minified works. The difference between the two is that minified code means that a file's size has been reduced by removing unnecessary characters in the code. Typically this is done by removing spaces, indentation, and comments, as well as by shortening variable names. Doing this improves the code's performance on the web and does not affect the normal function of the code. For this example, we'll select the minified option.

When we click on 'minified', this will trigger a pop-up box with the script tag for the CDN. Using the image below as an example, the most recent stable version of jQuery Core is 3.6.0, and the minified option has been highlighted with a black rectangle:

Select jQuery Core's most recent minified version for the CDN script

As noted earlier in this lesson, we will use version 3.5.1 in the projects that we walk you through in the curriculum. Here's the CDN script for version 3.5.1, found here:

<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>

integrity and crossorigin Attributes

Let's continue with our review. The integrity and crossorigin attributes in the script tag are used for Subresource Integrity (SRI) checking. According to srihash.org, SRI checking allows browsers to ensure that resources hosted on third-party servers (like jQuery's JavaScript library that we are accessing via CDN) have not been tampered with. Performing SRI checking is a best practice set by W3C, the World Wide Web Consortium, an international organization that sets standards for the web.

You do not need to retain any of the above information about the integrity and crossorigin attributes. However, it is interesting and you are welcome to read more on your own!

Ultimately, both approaches to loading jQuery into your project work well. CDNs are fast and reliable, however you will have to have an internet connection for it to work.

Using jQuery


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

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

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!

The jQuery Function and Event Handlers

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. A callback function is a function that is passed into another function as an argument. It might surprise you that functions can be arguments just like strings and numbers but this is actually a very powerful feature of JavaScript that we'll learn about later on in the program.

This callback function isn't called immediately, though. Instead, it's passed into the click() function. That means that when the event handler is triggered, the callback will be executed. In this case, when a user clicks on the element, the click() function will be triggered which in turn triggers the callback.

If this sounds complicated and confusing, that's totally expected - especially if you're new to coding. There are a lot of complicated things going on under the hood. Learning to drive is one thing - and it's not too hard. But learning how to build and maintain a car is a lot more work. Fortunately, jQuery does most of the work for us so we don't have to think about it. It's like focusing on driving instead of needing to build a car from scratch.

A Closer Look at Callback Functions

Inside the anonymous callback function, we can put whatever code we want. 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 heading.");
  alert("I told you, THIS IS A HEADING!");
});

If we break this down so we only look at the argument being passed into the click() function above, this is the argument:

function() {
  alert("This is a heading.");
  alert("I told you, THIS IS A HEADING!");
}

And that's exactly what a callback is. An argument that is a function.

This may seem like 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 like this, so you'll get the hang of it pretty quickly.

Before moving on, note the use of semicolons again. It may seem a bit confusing with the callback syntax, but we're really just doing the following in the code above:

jQuery("h1").click();

The code inside click() is another function - which doesn't need to have a semicolon after it because we don't need to add semicolons after function declarations. So this order of }); may be a little confusing at first, but it's only because one function is being called with another function as an argument.

jQuery(document).ready()

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-3.5.1.js"></script>
  <script src="js/scripts.js"></script>
  <title>HTML help</title>
</head>

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! Check out the new lines of code that we've added to scripts.js:

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

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

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

Here's the new code singled out from the code block above:

jQuery(document).ready(function() {
  ...
  // event handlers
  ...
})

Now let's break down what's happening in the code above:

  • When we write jQuery(document), we are telling jQuery to look at the HTML document.
  • And then we call the .ready() method on jQuery(document). This tells our JavaScript not to run until the document has finished loading.
  • When the document has finished loading, jQuery will run the anonymous callback function, function() {...}, that is passed into .ready().
  • And that callback 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. In our projects, we'll do this from now on.

Check out our page - it works again!

$(): a Shortcut for jQuery()

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 heading.");
  });

  $("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. It is how most people write the jQuery function, and this is how we'll be calling on the jQuery function in the rest of our projects.

Inspecting Event Listeners with Browser Dev Tools

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.

See the image below for an example. After right-clicking the <h1> tag and selecting the 'Event Listeners' tab, we can see that indeed there is a 'click' event listener attached to the <h1> tag.

This image shows how to inspect event listeners attached with an HTML element

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-3.5.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 heading.");
});

The part function() { alert("This is a heading."); } 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 heading.");
  });
});

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

Lesson 34 of 65
Last updated May 23, 2022