Our custom code will go in the second, currently empty, JavaScript file, which we included from the HTML using <script src="alice.js" type="text/javascript"></script>
. For this example, we only need three lines of code:
The fundamental operation in jQuery is selecting a part of the document. This is done with the $()
construct. Typically, it takes a string as a parameter, which can contain any CSS selector expression. In this case, we wish to find all parts of the document that have the poem-stanza
class applied to them; so the selector is very simple, but we will cover much more sophisticated options through the course of the book. We will step through the different ways of locating parts of a document in Chapter 2.
The $()
function is actually a factory for the jQuery object, which is the basic building block we will be working with from now on. The jQuery object encapsulates zero or more DOM elements, and allows us to interact with them in many different ways. In this case, we wish to modify the appearance of these parts of the page, and we will accomplish this by changing the classes applied to the poem text.
The .addClass()
method is fairly self-explanatory; it applies a CSS class to the part of the page that we have selected. Its only parameter is the name of the class to add. This method, and its counterpart, .removeClass()
, will allow us to easily observe jQuery in action as we explore the different selector expressions available to us. For now, our example simply adds the emphasized
class, which our stylesheet has defined as italicized text with a border.
Note that no iteration is necessary to add the class to all the poem stanzas. As we discussed, jQuery uses implicit iteration within methods such as .addClass()
, so a single function call is all it takes to alter all of the selected parts of the document.
Taken together, $()
and .addClass()
are enough for us to accomplish our goal of changing the appearance of the poem text. However, if this line of code is inserted alone in the document header, it will have no effect. JavaScript code is generally run as soon as it is encountered in the browser, and at the time the header is being processed, no HTML is yet present to style. We need to delay the execution of the code until after the DOM is available for our use.
The traditional mechanism for controlling when JavaScript code is run is to call the code from within event handlers. Many handlers are available for user-initiated events, such as mouse clicks and key presses. If we did not have jQuery available for our use, we would need to rely on the onload
handler, which fires after the page (along with all of its images) has been rendered. To trigger our code from the onload
event, we would place the code inside a function:
Then we would attach the function to the event by modifying the HTML <body>
tag to reference it:
This causes our code to run after the page is completely loaded.
There are drawbacks to this approach, though. We altered the HTML itself to effect this behavior change. This tight coupling of structure and function clutters the code, possibly requiring the same function calls to be repeated over many different pages, or in the case of other events such as mouse clicks, over every instance of an element on a page. Adding new behaviors would then require alterations in two different places, increasing the opportunity for error and complicating parallel workflows for designers and programmers.
To avoid this pitfall, jQuery allows us to schedule function calls for firing once the DOM is loaded—without waiting for images—with the $(document).ready()
construct. With our function defined as above, we can write:
This technique does not require any HTML modifications. Instead, the behavior is attached entirely from within the JavaScript file. We will learn how to respond to other types of user actions, divorcing their effects from the HTML structure as well, in Chapter 3.
This incarnation is still slightly wasteful, though, because the function emphasizePoemStanzas()
is defined only to be used immediately, and exactly once. This means that we have used an identifier in the global namespace of functions that we have to remember not to use again, and for little gain. JavaScript, like some other programming languages, has a way around this inefficiency called anonymous functions (sometimes also called lambda functions). We arrive back at the code as originally presented:
By using the function
keyword without a function name, we define a function exactly where it is needed, and not before. This removes clutter and brings us back down to three lines of JavaScript. This idiom is extremely convenient in jQuery code, as many methods take a function as an argument and such functions are rarely reusable.
When this syntax is used to define an anonymous function within the body of another function, a closure can be created. This is an advanced and powerful concept, but should be understood when making extensive use of nested function definitions as it can have unintended consequences and ramifications on memory use. This topic is discussed fully in Appendix C.