jQuery is a JavaScript library that helps web developers create JavaScript applications that work well in any browser. This book demonstrates how to use jQuery to reduce the amount of code you need to write and reduce the amount of testing that is required. Youll see how separation of presentation (CSS), markup (XHTML), and script (JavaScript and Ajax) in web pages is a crucial direction in web development for creating maintainable, accessible, cost-effective web sites. The featured full-color code syntax highlighting provides you with a visual reinforcement so you can see the various pieces and parts that make up each line and section of code for each language.
Read A Chapter
Chapter One
Introduction to jQuery
JavaScript frameworks have arisen as necessary and useful companions for client-side web development. Without JavaScript frameworks, client-side programming becomes a crater-filled minefield of cross-browser, cross-platform inconsistencies and idiosyncrasies. JavaScript frameworks pave over those craters and inconsistencies to create a seamless, enjoyable client-side programming experience.
The most important hole filled by a JavaScript framework is inconsistencies between Internet Explorer''s and the W3C''s standard Event APIs. jQuery fills in this hole by making a cross-browser Event API that is very similar to the W3C''s, adding some original helpful extensions of its own.
Another hole filled by most of the popular client-side JavaScript frameworks is the ability to select and traverse through nodes in the Document Object Model (DOM) using more than the very remedial selection and traversal
Click to read more...
Chapter One
Introduction to jQuery
JavaScript frameworks have arisen as necessary and useful companions for client-side web development. Without JavaScript frameworks, client-side programming becomes a crater-filled minefield of cross-browser, cross-platform inconsistencies and idiosyncrasies. JavaScript frameworks pave over those craters and inconsistencies to create a seamless, enjoyable client-side programming experience.
The most important hole filled by a JavaScript framework is inconsistencies between Internet Explorer''s and the W3C''s standard Event APIs. jQuery fills in this hole by making a cross-browser Event API that is very similar to the W3C''s, adding some original helpful extensions of its own.
Another hole filled by most of the popular client-side JavaScript frameworks is the ability to select and traverse through nodes in the Document Object Model (DOM) using more than the very remedial selection and traversal APIs that are provided by browsers'' default DOM implementations.
jQuery provides a selection mechanism that uses selector syntax like that used in cascading style sheets. However, not content to support only the standard selectors supported in CSS and even the new Selectors API implementations supported by WebKit and Internet Explorer 8, jQuery again extends the standard to support new, innovative, and useful selectors that make sense when using selectors to select DOM nodes.
In a nutshell, jQuery reduces significantly the amount of JavaScript programming and Q/A (quality assurance) you have to undertake. It takes what might take several lines of code to write, and more often than not reduces that to just one or a few lines of code. jQuery makes your JavaScript more intuitive and easier to understand. jQuery takes JavaScript programming (which at one time had a higher barrier of entry due to complexity and cross-browser, cross-platform idiosyncrasies) and makes it easier and more attractive to average web developers.
Throughout this book, I will discuss jQuery''s Application Programming Interface, or API. We''ll look in depth and up close at each little bit of programming syntax that enables jQuery to do what it does. With each new bit, I also provide simple, to-the-point examples that demonstrate how that bit works. I show you how to write JavaScript applications using jQuery, and by the end of this book, you too will be able to create Web 2.0 applications that function seamlessly across multiple browsers and platforms.
In this chapter, I begin discussion of jQuery by introducing what you get out of jQuery, who develops jQuery, how you obtain jQuery, and how you install jQuery and test that it is ready to use.
As I mentioned in the Introduction, I do not assume that you are a JavaScript expert in this book, but I do assume that you are familiar with basic JavaScript concepts, such as the DOM and attaching events. I will do my best to keep examples simple and to the point and avoid layering on thick programming jargon.
What Does jQuery Do for Me?
jQuery makes many tasks easier. Its simplistic, comprehensive API has the ability to completely change the way you write JavaScript, with the aim of consolidating and eliminating as many common and redundant tasks as possible. jQuery really shines in the following areas:
jQuery makes iterating and traversing the DOM much easier via its various built-in methods for doing the same.
jQuery makes selecting items from the DOM easier via its sophisticated, built-in ability to use selectors, just like you would use in CSS.
jQuery makes it really easy to add your own custom methods via its simple-to-understand plug-in architecture.
jQuery helps reduce redundancy in navigation and UI functionality, like tabs, CSS and markup-based pop-up dialogues, animations, and transitions, and lots of other things.
jQuery won''t do your laundry, walk the dog, or broker world peace (yet), but it does bring a lot to the table in terms of making client-side website development easier.
Is jQuery the only JavaScript framework? - no, certainly not. You can pick from several JavaScript frameworks: base2, Yahoo UI, Prototype, SproutCore, Dojo, and so on. I picked jQuery for this book simply because I enjoy its simplicity and lack of verbosity. On the other hand, among the other frameworks, you''ll find that there is a lot of similarity and each provides its own advantages in terms of unifying Event APIs, providing sophisticated selector and traversal implementations, and providing simple interfaces for redundant JavaScript-driven UI tasks.
In the past, I''ve been a big fan of base2, simply for its commitment to supporting W3C-sanctioned and de facto standard APIs seamlessly. But I have decided to focus on jQuery exclusively and exhaustively for this book because I think its popularity merits comprehensive coverage, which I''m able to present in a way that is more befitting novice programmers.
In a nutshell, jQuery blurs and even erases lines in some places that existed as barriers for true cross-browser, cross-platform development. It gives you a standard Event API, a standard Selectors API, useful traversal and enumeration methods, and a very useful UI library that work across the board in Internet Explorer, Safari, Firefox, and Opera on Windows, Mac, and Linux platforms.
That''s not to say that you won''t ever encounter cross-browser issues with your programs, but jQuery makes it much less likely and eliminates a hefty chunk of compatibility issues.
Who Develops jQuery?
I won''t spend a lot of time talking about the history of JavaScript frameworks, why they exist, and so on. I prefer to get straight to the point. That said, a brief mention of the people involved with developing jQuery is in order.
jQuery''s lead developer and creator is John Resig, whose website is located at www.ejohn.org. John resides in Boston, Massachusetts and is a JavaScript Evangelist for the Mozilla Corporation.
There are also several other people who have contributed to jQuery and continue to assist with its development. You can learn more about these people and what roles they played in jQuery''s development at http://docs.jquery.com/About/Contributors.
Obtaining jQuery
jQuery is a free, Open Source JavaScript Framework. The current stable, production release version, as of this writing, is 1.2.6. I use version 1.2.6 throughout the course of this book. Getting jQuery is easy - all you have to do is go to www.jquery.com and click on the "Download" link. You''ll see three options for downloading: a packed and gzipped version, an uncompressed version, and a packed version; these all refer to the same jQuery script. Download "uncompressed" if you want to be able to look at jQuery''s source code. Download "packed" if you, for whatever reason, are unable to use gzip compression. The packed version is the same JavaScript code minus all comments, white space, and line breaks. Otherwise, for the best possible download performance, the packed and gzipped version is the best.
Installing jQuery
Throughout this book, I will refer to the jQuery script as though it is installed at the following path: www.example.com/Library/jquery/jquery.js.
Therefore, if I were using the domain example.com, jQuery would have this path from the document root, /Source Code/jquery/jquery.js. You do not have to install jQuery at this exact path.
The following "Try It Out" assists you with installing jQuery by giving you an alternative dialogue when the script is properly installed.
Try It Out Installing and Testing jQuery Example 1-1
To install and test jQuery, follow these steps.
1. Download the jQuery script from www.jquery.com. Alternatively, I have also provided the jQuery script in this book''s source code download materials available for free from www.wrox.com.
2. Enter the following XHTML document, and save the document as Example 1-1.html. Adjust your path to jQuery appropriately; the path that I use reflects the path needed for the example to work when opened in a browser via the source code materials download made available for this book from www.wrox.com.
Link
jQuery is not loaded.
3. Enter the following JavaScript document, and save the document as Example 1-1.js: if ($) { $(document).ready( function() { $(''p'').addClass(''tmpFrameworkLoaded''); $(''p'').text(''jQuery successfully loaded and running!''); } ); }
4. Enter the following CSS document, and save the document as Example 1-1.css: body { font: 16px sans-serif; } p { color: red; border: 1px solid red; padding: 5px; margin: 5px; } p.tmpFrameworkLoaded { color: green; border: 1px solid green; }
The preceding code results in the screenshot that you see in Figure 1-1, if the installation was unsuccessful; and the screenshot in Figure 1-2, if the installation was successful.
In the preceding example, you installed and tested your installation of the jQuery framework. The XHTML document references a style sheet and a test JavaScript. The XHTML document contains just a single
element that contains the text "jQuery is not loaded." The style sheet has a rule that makes that text red with a red border around the
element.
The JavaScript that you included first looks for the jQuery object, which is contained in a single dollar sign. That one dollar sign contains all of jQuery''s functionality, which makes jQuery statements really short. If that''s too short for you, you can also substitute "jQuery" for the dollar sign, which would have made that JavaScript example look like this:
if (jQuery) { jQuery(document).ready( function() { jQuery(''p'').addClass(''tmpFrameworkLoaded''); jQuery(''p'').text(''jQuery successfully loaded and running!''); } ); }
An event is attached to jQuery''s ready event, which is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images. In old-time JavaScript, you would have made your JavaScript execute at page load, or the onload event. The onload event can be much slower, however, since it waits for all content and images to load before executing, instead of just content.
With an event attached to the ready event, you''re ready to do something with the document. In this case, once the document is loaded, jQuery selects the
element and gives it the class name tmpFrameworkLoaded. Then jQuery selects the
element again and changes its text content to say "jQuery successfully loaded and running!" The addition of the class name results in the
element having green text with a green border around the element.
The preceding is a pretty simple, cut-and-dry test of jQuery''s existence, and with this simple example, you see a huge difference with traditional, framework-less JavaScript. Without the jQuery framework, this is what the preceding example would have looked like:
window.onload = function() { var $p = document.getElementsByTagName(''p'')[0];
$p.className = ''tmpFrameworkLoaded'';
if ($p.innerText) { $p.innerText = ''jQuery successfully loaded and running!''; } else { $p.textContent = ''jQuery successfully loaded and running!''; } };
Programming Conventions
In web development, it''s common for professional web designers, web developers - and anyone with a job title whose day-to-day activities encompass the maintenance of source code - to adopt standards and conventions with regard to how the source code is written. Standardization bodies like the W3C, who define the languages that you use to create websites, already decide on some standards for you. Some standards are not written, but are rather de facto standards. De facto standards are standards that have become accepted throughout the industry, despite not appearing in any official document developed by a standards organization.
Throughout this book, I talk about standards, de facto and official, and how to develop and design web-based documents and even web-based applications that take those standards into account. For example, I talk extensively about how to separate behavior (JavaScript) from presentation (CSS) and structure (XHTML). JavaScript written in this way is commonly referred to as non-intrusive JavaScript - it''s non-intrusive because it supplements the content of a web document, and, were it turned off, the document would still be functional. CSS is used to handle all the presentational aspects of the document. And the structure of the document lives in semantically written XHTML. XHTML that is semantically written is organized meaningfully with the right markup elements and contains very little, if any at all, presentational components directly in the markup.
In addition to standards, I discuss how to develop web-based documents, taking into account different browser inconsistencies, discrepancies, and idiosyncrasies. There is some interactive functionality that nearly every browser handles differently; in those situations, other web professionals have already pioneered de facto standards that are used to bring all browsers into accord. The idea of a JavaScript foundational framework has become more popular and increasingly a dependency for so-called Web 2.0 applications, like the ones you''ll learn to develop using the jQuery framework.
Before I begin the discussion of jQuery, in the coming sections, I provide a generalized overview of programming conventions and good practice that should be followed.
XHTML and CSS Conventions
It''s important that your web documents be well-organized, cleanly written, and appropriately named and stored. This requires discipline and even an obsessive attention to the tiniest of details.
The following is a list of rules to abide by when creating XHTML and CSS documents:
Catch errors in XHTML and CSS.
When selecting ID and Class names, make sure that they are descriptive and are contained in a namespace. You never know when you might need to combine one project with another - name-spaces will help you to prevent conflicts.
When defining CSS, avoid using generic type selectors. Make your CSS more specific. This will also help with preventing conflicts.
Organize your files in a coherent manner. Group files from the same project in the same folder; separate multiple projects with multiple folders. Avoid creating huge file dumps that make it difficult to locate and associate files.
Avoid inaccessible markup. Stay away from frames, where possible. Organize your markup using semantically appropriate elements. Place paragraphs in
elements. Place lists in
or elements. Use
through
for headings, and so on.
If you are able to, also consider the loading efficiency of your documents. For development, use small, modularized files organized by the component; combine and compress those modularized files for a live production site.