31,19 €
To build interesting, interactive sites, developers are turning to JavaScript libraries such as jQuery to automate common tasks and simplify complicated ones. Because many web developers have more experience with HTML and CSS than with JavaScript, the library's design lends itself to a quick start for designers with little programming experience. Experienced programmers will also be aided by its conceptual consistency.Learning jQuery Third Edition is revised and updated for version 1.6 of jQuery. You will learn the basics of jQuery for adding interactions and animations to your pages. Even if previous attempts at writing JavaScript have left you baffled, this book will guide you past the pitfalls associated with AJAX, events, effects, and advanced JavaScript language features.Starting with an introduction to jQuery, you will first be shown how to write a functioning jQuery program in just three lines of code. Learn how to add impact to your actions through a set of simple visual effects and to create, copy, reassemble, and embellish content using jQuery's DOM modification methods. The book will step you through many detailed, real-world examples, and even equip you to extend the jQuery library itself with your own plug-ins.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Veröffentlichungsjahr: 2011
Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2011
Production Reference: 1160911
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK..
ISBN 978-1-84951-654-9
www.packtpub.com
Cover Image by Karl Swedberg (<[email protected]>)
Authors
Jonathan Chaffer
Karl Swedberg
Reviewers
Kaiser Ahmed
Kevin Boudloche
Carlos Estebes
Acquisition Editor
Sarah Cullington
Development Editor
Roger D'souza
Technical Editors
Llewellyn F. Rozario
Azharuddin Sheikh
Project Coordinator
Srimoyee Ghoshal
Proofreader
Linda Morris
Indexers
Tejal Daruwale
Rekha Nair
Graphics
Nilesh Mohite
Production Coordinators
Aparna Bhagat
Prachali Bhiwandkar
Cover Work
Aparna Bhagat
Prachali Bhiwandkar
I feel honored knowing that Karl Swedberg and Jonathan Chaffer undertook the task of writing Learning jQuery. As the first book about jQuery, it set the standard that other jQuery—and, really, other JavaScript books in general—have tried to match. It's consistently been one of the top selling JavaScript books since its release, in no small part due to its quality and attention to detail.
I'm especially pleased that it was Karl and Jonathan who wrote the book as I already knew them so well and knew that they would be perfect for the job. Being part of the core jQuery team, I've had the opportunity to come to know Karl quite well over the past couple years, and especially within the context of his book writing effort. Looking at the end result, it's clear that his skills as both a developer and a former English teacher were perfectly designed for this singular task.
I've also had the opportunity to meet both of them in person, a rare occurrence in the world of distributed Open Source projects, and they continue to be upstanding members of the jQuery community.
The jQuery library is used by so many different people in the jQuery community. The community is full of designers, developers, people who have experience programming, and those who don't. Even within the jQuery team, we have people from all backgrounds providing their feedback on the direction of the project. There is one thing that is common across all of jQuery's users, though: We are a community of developers and designers who want JavaScript development to be made simple.
It's almost a cliché, at this point, to say that an open source project is community-oriented, or that a project wants to focus on helping new users get started. However, it's not just an empty gesture for jQuery; it's the liquid-oxygen fuel for the project. We actually have more people in the jQuery team dedicated to managing the jQuery community, writing documentation, or writing plugins than actually maintaining the core code base. While the health of the library is incredibly important, the community surrounding that code is the difference between a floundering, mediocre project and one that will match and exceed your every need.
How we run the project, and how you use the code, is fundamentally very different from most open source projects—and most JavaScript libraries. The jQuery project and community is incredibly knowledgeable; we understand what makes jQuery a different programming experience and do our best to pass that knowledge on to fellow users.
The jQuery community isn't something that you can read about to understand; it's something that you actually have to participate in for it to fully sink in. I hope that you'll have the opportunity to partake in it. Come join us in our forums, mailing lists, and blogs and let us help guide you through the experience of getting to know jQuery better.
For me, jQuery is much more than a block of code. It's the sum total of experiences that have transpired over the years in order to make the library happen. The considerable ups and downs, the struggle of development together with the excitement of seeing it grow and succeed. Growing close with its users and fellow team members, understanding them and trying to grow and adapt.
When I first saw this book talk about jQuery and discuss it like a unified tool, as opposed to the experiences that it's come to encapsulate for me, I was both taken aback and excited. Seeing how others learn, understand, and mold jQuery to fit them is much of what makes the project so exhilarating.
I'm not the only one who enjoys jQuery on a level that is far different from a normal tool-user relationship. I don't know if I can properly encapsulate why this is, but I've seen it time and time again—the singular moment when a user's face lights up with the realization of just how much jQuery will help them.
There is a specific moment where it just clicks for a jQuery user, when they realize that this tool that they were using was in fact much, much more than just a simple tool all along—and suddenly their understanding of how to write dynamic web applications completely shifts. It's an incredible thing, and absolutely my favorite part of the jQuery project.
I hope you'll have the opportunity to experience this sensation as well.
John Resig
Creator of jQuery
Jonathan Chaffer is a member of Rapid Development Group, a web development firm located in Grand Rapids, Michigan. His work there includes overseeing and implementing projects in a wide variety of technologies, with an emphasis in PHP, MySQL, and JavaScript. He also leads on-site training seminars on the jQuery framework for web developers.
In the open-source community, Jonathan has been very active in the Drupal CMS project, which has adopted jQuery as its JavaScript framework of choice. He is the creator of the Content Construction Kit, a popular module for managing structured content on Drupal sites. He is responsible for major overhauls of Drupal's menu system and developer API reference.
Jonathan lives in Grand Rapids with his wife, Jennifer.
I would like to thank Jenny for her tireless enthusiasm and support, Karl for the motivation to continue writing when the spirit is weak, and the Ars Technica community for constant inspiration toward technical excellence. In addition, I'd like to thank Mike Henry and the Twisted Pixel team for producing consistently entertaining distractions in between writing sessions.
Karl Swedberg is a web developer at Fusionary Media in Grand Rapids, Michigan, where he spends much of his time making cool things happen with JavaScript. As a member of the jQuery team, Karl is responsible for maintaining the jQuery API site at api.jquery.com. He also publishes tutorials on his blog, learningjquery.com, and presents at workshops and conferences. When he isn't coding, Karl likes to hang out with his family, roast coffee in his garage, and exercise at the local cross-fit gym.
I wish to thank my wife, Sara, and my two children, Benjamin and Lucia, for all the joy that they bring into my life. Thanks also to Jonathan Chaffer for his patience and his willingness to write this book with me.
Many thanks to John Resig for creating the world's greatest JavaScript library and to all the others who have contributed their code, time, and expertise to the project. Thanks to the folks at Packt Publishing, the technical reviewers of this book, the jQuery Cabal, and the many others who have provided help and inspiration along the way.
Kaiser Ahmed is a professional web developer. He has gained his Bachelor's Degree from Khulna University of Engineering and Technology (KUET). He is also a co-founder of fully outsourcing company CyberXpress.Net Inc based on Bangladesh.
He has a wide breadth of technical skills, Internet knowledge, and experience across the spectrum of online development in the service of building and improving online properties for multiple clients. He enjoys creating site architecture and infrastructure, backend development using open source toolset (PHP, MySQL, Apache, Linux, and others (that is LAMP)), frontend development with CSS and HTML/XHTML.
He would like to thank his loving wife, Maria Akter, for her support.
Kevin Boudloche is a web developer out of Mississippi. He has been building web pages as a hobby for more than eight years and for three years professionally. Kevin's primary focus is front-end development and web application development.
Carlos Estebes is the founder of Ehxioz (http://ehxioz.com/) a Los Angeles-based software development startup that specializes in developing modern web applications and utilizing the latest web development technologies & methodologies. He has over 10 years of web development experience and holds a BSc in Computer Science from California State University, Los Angeles.
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
In 2005, inspired by pioneers in the field such as Dean Edwards and Simon Willison, John Resig put together a set of functions to make it easy to programmatically find elements on a web page and assign behaviors to them. By the time he first publicly announced his project in January 2006, he had added DOM modification and basic animations. He gave it the name jQuery to emphasize the central role of finding, or querying, parts of a web page and acting on them with JavaScript. In the few short years since then, jQuery has grown in its feature set, improved in its performance, and gained widespread adoption by many of the most popular sites on the Internet. While Resig remains the lead developer of the project, jQuery has blossomed, in true open-source fashion, to the point where it now boasts a core team of top-notch JavaScript developers, as well as a vibrant community of thousands of developers.
The jQuery JavaScript library can enhance your websites regardless of your background. It provides a wide range of features, an easy-to-learn syntax, and robust cross-platform compatibility in a single compact file. What's more, hundreds of plugins have been developed to extend jQuery's functionality, making it an essential tool for nearly every client-side scripting occasion.
Learning jQuery Third Edition provides a gentle introduction to jQuery concepts, allowing you to add interactions and animations to your pages—even if previous attempts at writing JavaScript have left you baffled. This book guides you past the pitfalls associated with Ajax, events, effects, and advanced JavaScript language features, and provides you with a brief reference to the jQuery library to return to again and again.
In Chapter 1, Getting Started, you'll get your feet wet with the jQuery JavaScript library. The chapter begins with a description of jQuery and what it can do for you. It then walks you through downloading and setting up the library, as well as writing your first script.
In Chapter 2, Selecting Elements, you'll learn how to use jQuery's selector expressions and DOM traversal methods to find elements on the page, wherever they may be. You'll use jQuery to apply styling to a diverse set of page elements, sometimes in a way that pure CSS cannot.
In Chapter 3, Handling Events, you'll use jQuery's event-handling mechanism to fire off behaviors when browser events occur. You'll see how jQuery makes it easy to attach events to elements unobtrusively, even before the page finishes loading. Also, you'll get an overview of deeper topics, such as event bubbling, delegation, and namespacing.
In Chapter 4, Styling and Animating, you'll be introduced to jQuery's animation techniques and see how to hide, show, and move page elements with effects that are both useful and pleasing to the eye.
In Chapter 5, Manipulating the DOM, you'll learn how to change your page on command. This chapter will teach you how to alter the very structure of an HTML document, as well as its content, on the fly.
In Chapter 6, Sending Data with Ajax, you'll discover the many ways in which jQuery makes it easy to access server-side functionality without resorting to clunky page refreshes. With the basic components of the library well in hand, you will be ready to explore how the library can expand to fit your needs.
In Chapter 7, Using Plugins, will show you how to find, install, and use plugins, including the powerful jQuery UI plugin library.
In Chapter 8, Developing Plugins, you'll learn how to take advantage of jQuery's impressive extension capabilities to develop your own plugins from the ground up. You'll create your own utility functions, add jQuery object methods, and discover the jQuery UI widget factory. Next, you'll take a second tour through jQuery's building blocks, learning more advanced techniques.
In Chapter 9, Advanced Selectors and Traversing, you'll refine your knowledge of selectors and traversals, gaining the ability to optimize selectors for performance, manipulate the DOM element stack, and write plugins that expand selecting and traversing capabilities.
In Chapter 10, Advanced Events, you'll dive further into techniques such as delegation and throttling that can greatly improve event handling performance. You'll also create custom and special events that add even more capabilities to the jQuery library.
In Chapter 11, Advanced Effects, you'll fine-tune the visual effects jQuery can provide by crafting custom easing functions and reacting to each step of an animation. You'll gain the ability to manipulate animations as they occur, and schedule actions with custom queuing.
In Chapter 12, Advanced DOM Manipulation, you'll get more practice modifying the DOM, with techniques such as attaching arbitrary data to elements. You'll also learn how to extend the way jQuery processes CSS properties on elements.
In Chapter 13, Advanced Ajax, you'll achieve a greater understanding of Ajax transactions, including the jQuery deferred object system for handling data that may become available at a later time.
In Appendix A, JavaScript Closures, you'll gain a solid understanding of closures in JavaScript—what they are and how you can use them to your advantage.
In Appendix B, Testing JavaScript with QUnit, you'll learn about the QUnit library for unit testing of JavaScript programs. This library will add to your toolkit for developing and maintaining highly sophisticated web applications.
In Appendix C, Quick Reference, you'll get a glimpse of the entire jQuery library, including every one of its methods and selector expressions. Its easy-to-scan format is perfect for those moments when you know what you want to do, but you're just unsure about the right method name or selector.
In order to run the example code demonstrated in this book, you need a modern web browser such as Mozilla Firefox, Apple Safari, Google Chrome, or Microsoft Internet Explorer.
To experiment with the examples and to work on the chapter-ending exercises, you will also need:
Additionally, to run some of the Ajax examples in Chapter 6 and beyond, you will need a PHP-enabled web server.
This book is for web designers who want to create interactive elements for their designs, and for developers who want to create the best user interface for their web applications. Basic JavaScript programming knowledge is required. You will need to know the basics of HTML and CSS, and should be comfortable with the syntax of JavaScript. No knowledge of jQuery is assumed, nor is experience with any other JavaScript libraries required.
By reading this book, you will become familiar with the functionality and syntax of jQuery 1.6.x, the latest version at the time of writing.
This book covers the functionality and syntax of jQuery 1.6.x, the latest version at the time of writing. The premise behind the library—providing an easy way to find elements on a web page and manipulate them—has not changed over the course of its development, but some syntax details and features have. This brief overview of the project history describes the most significant changes from version to version, which may prove helpful to readers working with legacy versions of the library.
Historical Details
Release notes for older jQuery versions can be found on the project's website at http://jquery.org/history.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "This code illustrates that we can pass any kind of expression into the console.log() method."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "The Console tab will be of most frequent use to us while learning jQuery, as shown in the following screenshot".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]>with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Today's World Wide Web is a dynamic environment, and its users set a high bar for both style and function of sites. To build interesting, interactive sites, developers are turning to JavaScript libraries such as jQuery to automate common tasks and simplify complicated ones. One reason for jQuery's popularity is its ability to assist in a wide range of tasks.
It can seem challenging to know where to begin because jQuery performs so many different functions. Yet, there is a coherence and symmetry to the design of the library; many of its concepts are borrowed from the structure of HTML and Cascading Style Sheets (CSS). The library's design lends itself to a quick start for designers with little programming experience as many of them have more experience with these technologies than they do with JavaScript. In fact, in this opening chapter, we'll write a functioning jQuery program in just three lines of code. On the other hand, experienced programmers will also be aided by this conceptual consistency, as we'll see in the later, more advanced chapters.
So let's look at what jQuery can do for us.
The jQuery library provides a general-purpose abstraction layer for common web scripting, and is, therefore, useful in almost every scripting situation. Its extensible nature means that we could never cover all possible uses and functions in a single book, as plugins are constantly being developed to add new abilities. The core features, though, assist us in accomplishing the following tasks:
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
With the resurgence of interest in dynamic HTML comes a proliferation of JavaScript frameworks. Some are specialized, focusing on just one or two of the above tasks. Others attempt to catalog every possible behavior and animation, and serve these all up pre-packaged. To maintain the wide range of features outlined above while remaining relatively compact, jQuery employs several strategies:
These strategies have kept the jQuery package slim—roughly 30 KB, compressed—while at the same time providing techniques to keep our custom code that uses the library compact.
The elegance of the library comes about partly by design, and partly due to the evolutionary process spurred by the vibrant community that has sprung up around the project. Users of jQuery gather to discuss not only the development of plugins, but also enhancements to the core library. The users and developers also assist in continually improving the official project documentation, which can be found at http://api.jquery.com.
Despite all of the efforts required to engineer such a flexible and robust system, the end product is free for all to use. This open source project is dually licensed under the MIT License (to permit free use of jQuery on any site and facilitate its use within proprietary software) and the GNU Public License (appropriate for inclusion in other GNU-licensed open-source projects).
Now that we have covered the range of features available to us with jQuery, we can examine how to put the library into action. To get started, we need a copy of jQuery.
No installation is required. To use jQuery, we just need a publicly available copy of the file, whether that copy is on an external site or our own. As JavaScript is an interpreted language, there is no compilation or build phase to worry about. Whenever we need a page to have jQuery available, we will simply refer to the file's location from a <script> element in the HTML document.
The official jQuery website (http://jquery.com/) always has the most up-to-date, stable version of the library, which can be downloaded right from the home page of the site. Several versions of jQuery may be available at any given moment; the most appropriate for us as site developers will be the latest uncompressed version of the library. This can be replaced with a compressed version in production environments.
As jQuery's popularity has grown, companies have made the file freely available through their Content Delivery Networks (CDNs). Most notably, Google (http://code.google.com/apis/ajaxlibs/documentation/), and Microsoft (http://www.asp.net/ajax/cdn) offer the file on powerful, low-latency servers distributed around the world for fast download regardless of the user's location. While a CDN-hosted copy of jQuery has speed advantages due to server distribution and caching, using a local copy can be convenient during development. Throughout this book we'll use a copy of the file stored on our own system, which will allow us to run our code whether we're connected to the Internet or not.
There are three pieces to most examples of jQuery usage: the HTML document, CSS files to style it, and JavaScript files to act on it. For our first example, we'll use a page with a book excerpt that has a number of classes applied to portions of it. This page includes a reference to the latest version of the jQuery library, which we have downloaded, renamed jquery.js, and placed in our local project directory, as follows:
File Paths
The actual layout of files on the server does not matter. References from one file to another just need to be adjusted to match the organization we choose. In most examples in this book, we will use relative paths to reference files (../images/foo.png) rather than absolute paths (/images/foo.png). This will allow the code to run locally without the need for a web server.
Immediately following the normal HTML preamble, the stylesheet is loaded. For this example, we'll use the following:
After the stylesheet is referenced, the JavaScript files are included. It is important that the script tag for the jQuery library be placed before the tag for our custom scripts; otherwise, the jQuery framework will not be available when our code attempts to reference it.
Throughout the rest of this book, only the relevant portions of HTML and CSS files will be printed. The files in their entirety are available at the book's companion website http://book.learningjquery.com.
Now we have a page that looks similar to the following screenshot:
We will use jQuery to apply a new style to the poem text.
This example is to demonstrate a simple use of jQuery. In real-world situations, this type of styling could be performed purely with CSS.
Our custom code will go in the second, currently empty, JavaScript file which we included from the HTML using <script src="01.js"></script>. For this example, we only need three lines of code, as follows:
The fundamental operation in jQuery is selecting a part of the document. This is done with the $() function. Typically, it takes a string as a parameter, which can contain any CSS selector expression. In this case, we wish to find all of the <div> elements in the document that have the poem-stanza class applied to them, so the selector is very simple. However, we will cover much more sophisticated options through the course of the book. We will step through many ways of locating parts of a document in Chapter 2, Selecting Elements.
When called, the $() function returns a new jQuery object instance, which is the basic building block we will be working with from now on. This 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, like most jQuery methods, is named self-descriptively; 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 highlight class, which our stylesheet has defined as italicized text with a gray background and 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.
With the $(document).ready() construct, jQuery allows us to schedule function calls for firing once the DOM is loaded—without necessarily waiting for images to fully render. While this event scheduling is possible without the aid of jQuery, $(document).ready() provides an especially elegant cross-browser solution that:
The .ready() method's parameter can accept a reference to an already defined function, as shown in the following code snippet:
Listing 1.1
However, as demonstrated in the original version of the script, and repeated in Listing 1.2, as follows, the method can also accept an anonymous function (sometimes also called a lambda function), as follows:
Listing 1.2
This anonymous function idiom is convenient in jQuery code for methods that take a function as an argument when that function isn't reusable. Moreover, the closure it creates can be an advanced and powerful tool. However, it may also have unintended consequences and ramifications on memory use, if not dealt with carefully. The topic of closures is discussed fully in Appendix A, JavaScript Closures.
Now that our JavaScript is in place, the page looks similar to the following screenshot:
The poem stanzas are now italicized and enclosed in boxes, as specified by the 01.css stylesheet, due to the insertion of the highlight class by the JavaScript code.
As this code comparison has shown, jQuery code is typically shorter and clearer than its basic JavaScript equivalent. However, this doesn't mean we will always write code that is free from bugs, or that we will intuitively understand what is happening on our pages at all times. Our jQuery coding experience will be much smoother with the assistance of standard development tools.
High-quality development tools are available in all modern browsers. We can feel free to use the environment that is most comfortable to us. Options include:
Each of these toolkits offers similar development features, including:
While the details of these features vary from one browser to the next, the general concepts remain constant. In this book, some examples will require the use of one of these toolkits; we will use Firebug for these demonstrations, but development tools for other browsers are fine alternatives.
Up-to-date instructions for installing and using Firebug can be found on the project's home page at http://getfirebug.com/. The tool is too involved to explore in great detail here, but a survey of some of the most relevant features will be useful to us.
Understanding these screenshots
Firebug is a quickly-evolving project, so the following screenshots may not exactly match your environment. Some of the labels and buttons are provided by the optional FireQuery add-on: http://firequery.binaryage.com/.
When Firebug is activated, a new panel appears offering information about the current page.
In the default HTML tab of this panel, we can see a representation of the page structure on the left side, and details of the selected element (such as the CSS rules that apply to it) on the right side. This tab is especially useful for investigating the structure of the page and debugging CSS issues, as shown in the following screenshot:
The Script tab allows us to view the contents of all loaded scripts on the page, as shown in the preceding screenshot. By clicking on a line number, we can set a breakpoint; when the script reaches a line with a breakpoint, it will pause until we resume execution with a button click. On the right side of the page, we can enter a list of variables and expressions we wish to know the value of at any time.
The Console tab will be of most frequent use to us while learning jQuery, as shown in the following screenshot. A field at the bottom of the panel allows us to enter any JavaScript statement, and the result of the statement is then presented in the panel:
In this example, we have performed the same jQuery selector as in Listing 1.2, but have not performed any action on the selected elements. Even so, the statement gives us interesting information. We see that the result of the selector is a jQuery object pointing to two .poem-stanza elements on the page. We can use this console feature to quickly try out jQuery code at any time, right from within the browser.
In addition, we can interact with this console directly from our code, using the console.log() method, as follows:
Listing 1.4
This code illustrates that we can pass any kind of expression into the console.log() method. Simple values such as strings and numbers are printed directly, and more complicated values such as jQuery objects are nicely formatted for our inspection, as shown in the following screenshot:
This console.log() function (which works in each of the browser developer tools we mentioned) is a convenient alternative to the JavaScript alert() function, and will be very useful as we test our jQuery code.
We now have an idea of why a developer would choose to use a JavaScript framework rather than writing all code from scratch, even for the most basic tasks. We also have seen some of the ways in which jQuery excels as a framework, why we might choose it over other options, and in general which tasks jQuery makes easier.
In this chapter, we have learned how to make jQuery available to JavaScript code on our web page, use the $() function to locate a part of the page that has a given class, call .addClass() to apply additional styling to this part of the page, and invoke $(document).ready() to cause this code to execute upon the loading of the page. We have also explored the development tools we will be relying on when writing, testing, and debugging our jQuery code.
The simple example we have been using demonstrates how jQuery works, but is not very useful in real-world situations. In the next chapter, we will expand on the code here by exploring jQuery's sophisticated selector language, finding practical uses for this technique.
The jQuery library harnesses the power of Cascading Style Sheets (CSS)selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM). In this chapter, we will explore a few of these selectors, as well as jQuery's own custom selectors. We'll also look at jQuery's DOM traversal methods that provide even greater flexibility for getting what we want.
One of the most powerful aspects of jQuery is its ability to make selecting elements in the DOM easy. The Document Object Model serves as the interface between JavaScript and a web page; it provides a representation of the source HTML as a network of objects rather than as plain text.
This network takes the form of a "family tree" of elements on the page. When we refer to the relationships that elements have with one another, we use the same terminology that we use when referring to family relationships: parents, children, and so on. A simple example can help us understand how the family tree metaphor applies to a document, as follows:
Here, <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>. The <head> and <body> elements are not only descendants, but children of <html>, as well. Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent. The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other, as shown in the following diagram:
To help visualize the family tree structure of the DOM, you can use a number of software tools, such as the Firebug plugin for Firefox, or the Web Inspector in Safari or Chrome.
With this tree of elements at our disposal, we'll be able to use jQuery to efficiently locate any set of elements on the page. Our tools to achieve this are jQuery selectors and traversal methods.
An important point to note, before we begin, is that the resulting set of elements from selectors and methods is always wrapped in a jQuery object. These jQuery objects are very easy to work with when we want to actually do something with the things that we find on a page. We can easily bind events to these objects and add slick effects to them, as well as chain multiple modifications or effects together. Nevertheless, jQuery objects are different from regular DOM elements or node lists, and as such do not necessarily provide the same methods and properties for some tasks. In the final part of this chapter, therefore, we will look at ways to directly access the DOM elements that are wrapped in a jQuery object.
No matter which type of selector we want to use in jQuery, we always start with the same function: $(). This function typically accepts a CSS selector as its sole parameter, and serves as a factory, returning a new jQuery object pointing to the corresponding elements on the page. Just about anything that can be used in a stylesheet can also be passed as a string to this function, allowing us to apply jQuery methods to the matched set of elements.
Making jQuery play well with other JavaScript libraries
In jQuery, the dollar sign $ is simply an "alias" for jQuery. As a $() function is very common in JavaScript libraries, conflicts could arise if more than one of these libraries were being used in a given page. We can avoid such conflicts by replacing every instance of $ with jQuery in our custom jQuery code. Additional solutions to this problem are addressed in Chapter 10, Advanced Events.
The three primary building blocks of selectors are tag name, ID, and class. They can be used either on their own or in combination with others. The following simple examples illustrate how these three selectors appear in code:
Selector Type
CSS
jQuery
What It Does
Tag name
p { }
$('p')
Selects all paragraphs in the document
ID
#some-id { }
$('#some-id')
Selects the single element in the document that has an ID of some-id
Class
.some-class { }
$('.some-class')
Selects all elements in the document that have a class of some-class
As mentioned in Chapter 1, Getting Started, when we call methods of a jQuery object, the elements referred to by the selector we passed to $() are looped through automatically and implicitly. Therefore, we can usually avoid explicit iteration, such as a for loop, that is so often required in DOM scripting.
Now that we have covered the basics, we're ready to start exploring some more powerful uses of selectors.
