How jQuery Works

In this lesson, we shall delve deeper into the workings of jQuery. Let's begin!

We'll cover the following...

HOW IT WORKS

The key to the behavior you experienced is the script you added in step 4.

This script carries out two things.

  1. First, it extends each <h1> element with a <span> tag that holds the plus or minus sign indicating the collapsed or expanded state of the heading.
  2. Second, it describes the function that responds to the click events.

The script is very concise due to jQuery. The first <script> element you added in step 4 loads jQuery. The second script contains the magic.

Let’s see how it works line by line.

$(document).ready(function () {
$('h1').prepend('<span class="node">-</span>');
$('h1').click(
function () {
var node = $(this).children('.node');
$(this).next().fadeToggle(500, 'swing',
function () {
var mark = node.text();
mark = mark === '-' ? '+' : '-';
node.text(mark);
});
})
});

The $ symbol used in this script is an alias to the jQuery JavaScript object that can be used to access the functions and variables defined in the library.

  • Line 1 defines a function that is executed when the page is ...