Basics of jQuery

jQuery is a JavaScript library. A library is code written by a third party that contains useful functions and objects. You include the library in any project you are working on by loading a script file containing the library before loading any script files of your own.

<script src="https://ajax.googleapis.com/ajax/libs/jQuery/1.12.4/jQuery.min.js"></script>

This script element must appear in your HTML file before any script elements that load your own scripts.

Unlike other JavaScript files we load, we will not be loading the jQuery JavaScript file from the same folder as our other project files. Instead, we will ask our page to download jQuery from a content delivery network, or CDN. In this case we are using Google as our content server.

Note also that we will be using jQuery version 1.12 in this course. There are more recent versions available, but version 1.12 is closest to the version that the author describes in the JavaScript text book.

These notes will introduce you to the main concepts in the jQuery library, and then illustrate those concepts by means of an example.

jQuery selectors

We have already seen that a primary application of JavaScript in the browser is to enable us to interact with elements in the HTML page. We can do this because JavaScript automatically constructs a model of all of the elements in the page called the document object model, or DOM. We then can use JavaScript DOM commands to locate DOM objects on the page, and then access or modify their properties. We can also use standard DOM manipulation methods to add and remove elements from the page.

jQuery is a library that is designed to allow us to carry out all of these operations in a simpler and more straightforward way.

As we have seen, the first step in any DOM manipulation is to locate the element we want to interact with. jQuery makes it easy to do this by using jQuery selectors. These selectors are intentionally designed to look a lot like CSS selectors. Since you already know how to use CSS selectors to target a specific element or group of elements, jQuery allows you to reuse that skill.

To use a selector to target an element in jQuery, we make use of a special function that the jQuery provides, the $() function. We pass this function a text string containing the selector, and the $() function returns a jQuery object to us.

Here is an example. To target a tbody element with the id of menu we use

$('tbody#menu')

or simply

$('#menu')

The $() function can return either a single element or a group of elements. For example, to target every paragraph in a document we would do

$('p')

jQuery also offers some additional selector elements that allow you to target more specific items. For example, suppose we want to target the first row in the tbody with the id of menu. The selector

$('tbody#menu tr:first')

will do that.

Using jQuery to make new elements

Another use of the $() function is to make new elements. In cases where you want to append a new element to an existing element, you will need to start by making that new element. Here is an example that demonstrates how to do that. Suppose we have a select element in our document with an id of colors, and that we want to append a new option to the select. The code sample below shows how to do that:

var list, newEntry;
list = $('select#colors'); // Locate the element with id of color
newEntry = $('<option>'); // Make a new option element
list.append(newEntry); // Append the new option to the select

This example is not yet complete, because we will also want to give the new option element a value and some content. We will see how to do that in the section below.

Adding, removing, and modifying elements

Once you have used a jQuery selector to identify the element you want to work with, you can use some jQuery object methods to manipulate that element.

As we saw in the example above, the append() method allows us to add new child elements to an existing element.

We can remove elements with the remove() method. To do this, we locate the element we want to remove via a selector, and then tell the element to remove itself. For example, if we wanted to remove the paragraph with the id of temp from our document, we would do

var p = $('p#temp'); // Locate the paragraph with an id of temp
p.remove(); // Tell the paragraph to remove itself

The extensive range of selectors available in jQuery make it easy to target just the element you want to manipulate. Another example is code to remove the last paragraph from the div with an id of column1:

var p = $('div#column1 p:last'); // Locate last p in the div
                                 // with an id of column1
p.remove(); // Tell that paragraph to remove itself

jQuery also has text(), html(), attr(), and val() methods that you can use to access the contents or attributes of elements you select. All of these methods come in two forms: an access form (which takes no parameters), which allows you read contents, and a setter form (which takes a parameter), which allows you to set the content. Here are some examples. The first example reads the value of the currently selected option in a select element:

var choice, x;
choice = $('select#size'); // Target the select element
                            // with an id of size
x = choice.val(); // Get the value of our selected option

The next example sets both the value and the text of the last option in the same select element.

var lastOption = $('select#size option:last');
lastOption.attr('value','XL'); // Set the value attribute to 'XL'
lastOption.text('Extra Large'); // Set the text of the option

The final example adds a new row to a table. To do this, we target the table, create a new tr element, use the html() method to put data in that row, and then finally append the new row to the table.

var table, newRow;
table = $('table#menu'); // Select the table with an id of menu
newRow = $('<tr>'); // Make a new row
newRow.html('<td>Soup</td><td>$2.50</td>'); // Add content
table.append(newRow); // Append the new row to the table

Chaining

Another convenient feature of jQuery methods is that they can be chained. In this technique we call several methods on the same object, one right after another. For example, suppose we wanted to both change the text content and add a CSS class to the last item in a ul with the id of options. The following statement does all of that at once:

$('ul#options li:last').text('Buy groceries: done').addClass('cool');

Chaining works because every single jQuery method returns the object after modifying it. That means that the text() method will pass the object along to the addClass() method.

Targeting and manipulating multiple elements

Just as in CSS, you can use a selector in jQuery to target several elements at once. Here is a somewhat extreme example. The jQuery selector 'p' targets all of the paragraphs in a document, which means that $('p') would produce a jQuery list of all of those paragraphs. If we then applied an operation to that list, the operation would affect every element in that list:

$('p').remove(); // Remove every paragraph in the document

Event handling with jQuery

You can also use jQuery to attach event handler functions to elements. You do this by calling the click() method on a jQuery object, and passing it the name of the function that will be doing the event handling. For example, suppose we have set up a function named doStuff, and we want that function to be triggered when the user clicks on a button with an id of doIt. Here is the jQuery code to set this up:

function doStuff() {
  // Do something exciting
}

$('button#doIt').click(doStuff);

Some event handler functions may need to access the element that the handler is attached to. You can do that by using the construction $(this) to turn the element into a jQuery object for further manipulation using jQuery methods. Here is a somewhat silly example. Suppose we have a button with an id of button1, and we want to attach an event handler to the button that causes the button text to change to 'Click me again' when we click on the button. Here is how to do that:

function doClick() {
  $(this).text('Click me again');
}

$('button#button1').click(doClick);

The jQuery equivalent of our usual code

window.addEventListener('load',setUp,false);

that triggers the setUp function when the page has finished loading is

$(document).ready(setUp);

Summary: jQuery vs Plain JavaScript

The examples below summarize all of the JavaScript DOM manipulations we have seen so for. In each case the jQuery equivalent is simpler.

Attach function to button

// Plain JavaScript
computeButton = document.getElementById('compute');
computeButton.addEventListener('click',computeHandler,false);
// jQuery
$('#compute').click(computeHandler);

Get value from text field or select element

// Plain JavaScript
intensitySelector = document.getElementById('intensity');
intensity = intensitySelector.value;
// jQuery
intensity = $('#intensity').val();

Place text in an element

// Plain JavaScript
resultPar = document.getElementById('result');
resultPar.textContent = 'This activity will burn ' + calories + ' calories.';
// jQuery
resultText = 'This activity will burn ' + calories + ' calories.';
$('#result').text(resultText)

Set up startUp function

// Plain JavaScript
window.addEventListener('load',setup,false);
// jQuery
$(document).ready(setUp);

Example: Arithmetic Quiz

The example page linked above implements a simple arithmetic quiz. The quiz displays a series of questions, and the possible responses for each question are linked to buttons below the question. The user answers the questions by clicking the buttons.

When the user has answered all of the questions the page shows how many questions they got right.

The JavaScript code uses a number of variables to store the questions and keep track of the current state of the quiz.

var problems = [{question:'1+1',options:['0','1','2'],answer:'2'},
  {question:'12-3',options:['12','9','6'],answer:'9'},
  {question:'5*6',options:['15','18','30'],answer:'30'},
  {question:'124/4',options:['31','62','124'],answer:'31'},
  {question:'15*5',options:['155','75','65'],answer:'75'},
  {question:'183+37',options:['210','220','230'],answer:'220'}];
var n = 0; // The current problem number
var correct = 0;

An interesting feature of this example is the fact that all three of the answer buttons are linked to the same function in the JavaScript code.

$('#one').click(answer);
$('#two').click(answer);
$('#three').click(answer);

The answer() function uses the jQuery construct $(this).text() to get the text content of the button the user clicked. By comparing that text against the correct answer for the current question the code can tell whether or not the user got the question right.

function answer() {
  if($(this).text() == problems[n].answer)
    correct = correct+1;
  if(n < 5) {
    n = n + 1;
    displayProblem();
  } else {
    $('#questions').hide();
    $('#score').text(correct);
    $('#results').show();
  }
}

The answer() function also advances the quiz to the next problem, or shows the final results after the user has answered the last question.

The program uses the jQuery hide() and show() methods to hide and show divs on the screen. When the user has answered all of the questions, the answer() function will hide the div that shows the questions and shows the div that presents the final results.