jQuery is a library written in Javascript that is specialized for changing web documents on the fly. It is one of the most used libraries on the Web. If you need a more gentle introduction to jQuery, read Chapter 1 (and more) from our book, Head First jQuery.

Interactive Example

Once you have completed reading these notes and perhaps the book chapter as well, you might want to test your learning by trying to add jQuery code to this HTML page (you'll need to save it on your computer first, by right-clicking and choosing Save Link as...), so that you gradually build a page that displays the behavior shown in the screencast below. You can do so without adding a single line to the HTML or CSS portions of the file, but only with jQuery code. The solution can be found at the end of the notes.

jQuery Basics

1. Include jQuery in a webpage

In order to use jQuery in a webpage, we need to include it with the <script> tag. The library itself is a big Javascript file with hundreds of lines of code. We can either download this file from the jQuery website, or we can use an absolute URL to some web server that keeps a copy of the library online. For simplicity, we will do the latter. Here is how we will include jQuery in our programs:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

As of these notes, the most current version of jQuery is 1.11.2. In your reading or examples from the Web, you will notice other version numbers. The .min part of the filename means mininfied. This refers to the practice of deleting all newlines and other space to reduce file size. If you open this file, you'll notice that it doesn't show the structure of a normal Javascript program with indentation and nesting. Thus, it is not for human consumption.

2. jQuery wrapper

Once we have the jQuery library linked to our page, we can start using its main method, the jQuery Wrapper. This is a function that has two forms, one is more used than the other:

// Short form used more often
$()

// Long form  used rarely
jQuery()

There are three things we can do with this function, they are listed below in order of most common to less common:

// Usage 1: Select elements from the DOM, using CSS selector phrases

$("h1");
$("nav ul li");
$("li:nth-of-type(2)");

// Usage 2: Create new HTML elements on the fly
$("<p>It's a rainy day</p>").appendTo($("body"))

// or
$("<p>").text("It's a sunny day")
              .appendTo($("body"));

// Usage 3: Access elements through their variable names
$(document);
$(this);

var header = $("header");
$(header).append("<h1>Welcome guest!</p>")

Being able to distinguish between these three usages, it's helpful to understand code written from others.

3. Method Chaining

The jQuery wrapper function always returns a value, which is an array. Sometimes this array might be empty, sometimes it has one element, and sometimes it has multiple elements.

Knowing that the jQuery wrapper always returns something is very useful for chaining jQuery methods. This is done to avoid storing results in temporary variables. Here is how an example of chaining looks like:

// create a new element and add it to the body tag
$("<p>").appendTo($("body"))
      .text("Just added a new paragraph")     // put some text to this element
      .css("font-size", "30pt");              // add some style      

The first call to $("p") created a new element and returned it. To the returned result, we applied the method .appendTo(), which after performing its work (appending the element to the body), still returned the original p element, which in turn invoked the method .text(), in order to add text to the element. This method also returned the p element, now with some inner text, and to this object the method .css() was applied to change the font size of the text.

4. Is the DOM ready?

An important question is when should our jQuery code be executed. Putting the code in different parts of the HTML file might have different effects on the page, based on when the browser reads and interprets the code. This is why, normally, the jQuery code should be executed only after the DOM has been created and is ready for dynamic manipulation.

Most examples you'll see in the provided reading, will show code usually wrapped in a big event handler for the document object, as shown below:

$(document).ready(function(){

  // all other jQuery code goes here

});

This code is complex to understand. It uses the jQuery wrapper function with an object, to the result it applies the method ready() (which is triggered when the DOM is ready), and to this method it passes as an argument an anonymous function. Notice that the final line is });.

Avoiding $(document).ready(function(){..});

Since the syntax for this event handler is complex and difficult to remember, we'll use a trick. We will always put our jQuery code at the very end of the HTML file, just before the end tag for body. This way, we know that the previous HTML lines have been already processed by the browser and the DOM is ready.

If you put the jQuery code (or the script tag referring to your jQuery code) anywhere else in the HTML file, you'll run into the problem of the DOM not being ready and your code will not work.

Javascript versus jQuery

It is a fair question to ask, why use jQuery. The reason is simple, it allows you to write less code to achieve the same things. jQuery itself is completely written in Javascript, however, it encapsulates in methods some of the most common activities that one would have to code and code over again for every program. jQuery is a perfect example of the big ideas of abstraction and modularity which are at the heart of computation.

Below is a table of some one-to-one mapping between Javascript code we have seen and jQuery method calls.

Javascript Code jQuery Code
 window.onload = onDocumentReady;
 function onDocumentReady() {
     // body of function 
 }
$(document).ready(function(){
  // body of function
});
document.querySelector("nav ul")	
$("nav ul");
document.querySelector("h1").innerHTML = "Welcome";	
$("h1").text("Welcome");
var button = document.querySelector("button");
button.onclick = function() {
  // body of function
}
$("button").click(function() { ...});
document.querySelector("h1").style.color = "red";	
$("h1").css("color", "red")


As you can notice, all the Javascript examples can be written in less code with jQuery.

Some jQuery Methods

Here is a list of jQuery methods used in our interactive example (or other methods that are useful).

  • .ready()
  • .append()
  • .appendTo()
  • .click()
  • .show()
  • .hide()
  • .text()
  • .attr()
  • .val() // for input fields
  • .parent()
  • .clone()
  • .addClass()
  • .removeClass()
  • .find()

To see more examples and explanations for these methods, you should consult the jQuery API documentation.

Solution for the jQuery problem

Here is the solution for the example shown in the screencast. HTML, CSS, and jQuery are in the same file, just because it is easier in this case to download the solution. Usually, you should have them in separate files.