Learning jQuery
By Jonathan Chaffer and Karl Swedberg
4/5
()
About this ebook
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.
LearningjQuery - Fourth Edition is revised and updated version 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 take you through many detailed, real-world examples, and even equip you to extend the jQuery library itself with your own plug-ins.
ApproachWe will step through each of the core concepts of the jQuery library, building an overall picture of its capabilities. Once you have thoroughly covered the basics, the book returns to each concept to cover more advanced examples and techniques.
Who this book is forThis 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 and knowledge of HTML and CSS is required. No knowledge of jQuery is assumed, nor is experience with any other JavaScript libraries.
Jonathan Chaffer
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.
Read more from Jonathan Chaffer
Learning jQuery 3 - Fifth Edition Rating: 0 out of 5 stars0 ratings
Related to Learning jQuery
Related ebooks
Object-Oriented JavaScript Rating: 4 out of 5 stars4/5Responsive Web Design with HTML5 and CSS3 - Second Edition Rating: 4 out of 5 stars4/5JavaScript : Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsObject-Oriented JavaScript - Third Edition Rating: 4 out of 5 stars4/5Java Programming: 24-Hour Trainer Rating: 0 out of 5 stars0 ratingsJavaScript and AJAX For Dummies Rating: 4 out of 5 stars4/5Web Application Development with MEAN Rating: 0 out of 5 stars0 ratingsMySQL for Python Rating: 5 out of 5 stars5/5TypeScript: Modern JavaScript Development Rating: 0 out of 5 stars0 ratingsMastering Django: Core Rating: 0 out of 5 stars0 ratingsMastering JavaScript Rating: 4 out of 5 stars4/5Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications, and libraries Rating: 3 out of 5 stars3/5JavaScript Unlocked Rating: 5 out of 5 stars5/5JavaScript Enlightenment Rating: 4 out of 5 stars4/5Learning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5JavaScript and JSON Essentials Rating: 5 out of 5 stars5/550 Recipes for Programming Node.js Rating: 3 out of 5 stars3/5Introduction to PHP Web Services: PHP, JavaScript, MySQL, SOAP, RESTful, JSON, XML, WSDL Rating: 0 out of 5 stars0 ratingsProfessional JavaScript for Web Developers Rating: 0 out of 5 stars0 ratingsJavaScript Security Rating: 4 out of 5 stars4/5React: Building Modern Web Applications Rating: 5 out of 5 stars5/5Bootstrap By Example Rating: 0 out of 5 stars0 ratingsModern JavaScript Applications Rating: 0 out of 5 stars0 ratingsJavaScript JSON Cookbook Rating: 0 out of 5 stars0 ratingsJavaScript: Tips and Tricks to Programming Code with Javascript Rating: 0 out of 5 stars0 ratingsResponsive Web Design with HTML5 and CSS3 Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Mastering JavaScript Design Patterns Rating: 4 out of 5 stars4/5JavaScript: Best Practices to Programming Code with JavaScript: JavaScript Computer Programming, #3 Rating: 0 out of 5 stars0 ratings
Programming For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsC# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsThe Most Concise Step-By-Step Guide To ChatGPT Ever Rating: 3 out of 5 stars3/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsLinux Command-Line Tips & Tricks Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Learning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5
Reviews for Learning jQuery
10 ratings0 reviews
Book preview
Learning jQuery - Jonathan Chaffer
Table of Contents
Learning jQuery Fourth Edition
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started
What jQuery does
Why jQuery works well
Making our first jQuery-powered web page
Downloading jQuery
Deciding on the version of jQuery to use
Setting up jQuery in an HTML document
Adding our jQuery code
Finding the poem text
Injecting the new class
Executing the code
The finished product
Plain JavaScript versus jQuery
Using development tools
Chrome Developer Tools
Summary
2. Selecting Elements
Understanding the DOM
Using the $() function
CSS selectors
Styling list-item levels
Attribute selectors
Styling links
Custom selectors
Styling alternate rows
Finding elements based on textual content
Form selectors
DOM traversal methods
Styling specific cells
Chaining
Accessing DOM elements
Summary
Further reading
Exercises
3. Handling Events
Performing tasks on page load
Timing of code execution
Handling multiple scripts on one page
Alternate syntax for .ready()
Passing an argument to the .ready() callback
Handling simple events
A simple style switcher
Enabling the other buttons
Making use of the event handler context
Consolidating code using the event context
Shorthand events
Showing and hiding advanced features
Event propagation
The journey of an event
Side effects of event bubbling
Altering the journey – the event object
Event targets
Stopping event propagation
Preventing default actions
Delegating events
Using built-in event-delegation capabilities
Removing an event handler
Giving namespaces to event handlers
Rebinding events
Simulating user interaction
Reacting to keyboard events
Summary
Further reading
Exercises
4. Styling and Animating
Modifying CSS with inline properties
Setting computed style-property values
Using vendor-specific style properties
Hiding and showing elements
Effects and duration
Speeding in
Fading in and fading out
Sliding up and sliding down
Toggling visibility
Creating custom animations
Building effects by hand
Animating multiple properties at once
Positioning with CSS
Simultaneous versus queued effects
Working with a single set of elements
Bypassing the queue
Queuing effects manually
Working with multiple sets of elements
Queuing with callbacks
In a nutshell
Summary
Further reading
Exercises
5. Manipulating the DOM
Manipulating attributes and properties
Non-class attributes
Value callbacks
DOM element properties
The value of form controls
DOM tree manipulation
The $() function revisited
Creating new elements
Inserting new elements
Moving elements
Wrapping elements
Explicit iteration
Using inverted insertion methods
Copying elements
Cloning for pull quotes
Content getter and setter methods
DOM manipulation methods in a nutshell
Summary
Further reading
Exercises
6. Sending Data with Ajax
Loading data on demand
Appending HTML
Working with JavaScript objects
Retrieving JSON
Using global jQuery functions
Executing a script
Loading an XML document
Choosing a data format
Passing data to the server
Performing a GET request
Performing a POST request
Serializing a form
Delivering different content for Ajax requests
Keeping an eye on the request
Error handling
Ajax and events
Security limitations
Using JSONP for remote data
Exploring additional options
The low-level Ajax method
Modifying default options
Loading parts of an HTML page
Summary
Further reading
Exercises
7. Using Plugins
Finding plugins and help
Using a plugin
Downloading and referencing the Cycle plugin
Calling a plugin method
Specifying plugin method parameters
Modifying parameter defaults
Other types of plugins
Custom selectors
Global function plugins
The jQuery UI plugin library
Effects
Color animations
Class animations
Advanced easing
Additional effects
Interaction components
Widgets
jQuery UI ThemeRoller
The jQuery Mobile plugin library
HTML5 custom data attributes
Mobile navigation
Delivering multiple pages in one document
Interactive elements
List views
Toolbar buttons
Advanced features
Summary
Exercises
8. Developing Plugins
Using the dollar ($) alias in plugins
Adding new global functions
Adding multiple functions
Extending the global jQuery object
Isolating functions within namespaces
Adding jQuery object methods
Object method context
Implicit iteration
Enabling method chaining
Providing flexible method parameters
The options object
Default parameter values
Callback functions
Customizable defaults
Creating plugins with the jQuery UI widget factory
Creating a widget
Destroying widgets
Enabling and disabling widgets
Accepting widget options
Adding submethods
Triggering widget events
Plugin design recommendations
Distributing a plugin
Summary
Exercises
9. Advanced Selectors and Traversing
Selecting and traversing revisited
Dynamic table filtering
Striping table rows
Combining filtering and striping
More selectors and traversal methods
Customizing and optimizing selectors
Writing a custom selector plugin
Selector performance
The Sizzle selector implementation
Testing selector speed
DOM traversal under the hood
jQuery object properties
The DOM element stack
Writing a DOM traversal method plugin
DOM traversal performance
Improving performance using chaining
Improving performance with caching
Summary
Further reading
Exercises
10. Advanced Events
Revisiting events
Loading additional pages of data
Displaying data on hovering
Event delegation
Using jQuery's delegation capabilities
Choosing a delegation scope
Delegating early
Defining custom events
Infinite scrolling
Custom event parameters
Throttling events
Other ways to perform throttling
Extending events
More about special events
Summary
Further reading
Exercises
11. Advanced Effects
Animation revisited
Observing and interrupting animations
Determining the animation state
Halting a running animation
Caution when halting animations
Using global effect properties
Disabling all effects
Defining effect durations
Multiproperty easing
Using deferred objects
Animation promises
Taking fine-grained control of animations
Summary
Further reading
Exercises
12. Advanced DOM Manipulation
Sorting table rows
Sorting tables on the server
Sorting tables using Ajax
Sorting tables within the browser
Moving and inserting elements revisited
Adding links around existing text
Sorting simple JavaScript arrays
Sorting DOM elements
Storing data alongside DOM elements
Performing additional precomputation
Storing non-string data
Alternating sort directions
Using HTML5 custom data attributes
Sorting and building rows with JSON
Modifying the JSON object
Rebuilding content on demand
Revisiting attribute manipulation
Using shorthand element-creation syntax
DOM manipulation hooks
Writing a CSS hook
Summary
Further reading
Exercises
13. Advanced Ajax
Implementing progressive enhancement with Ajax
Harvesting JSONP data
Handling Ajax errors
Using the jqXHR object
Ajax promises
Caching responses
Throttling Ajax requests
Extending Ajax capabilities
Data type converters
Adding Ajax prefilters
Defining alternate transports
Summary
Further reading
Exercises
A. JavaScript Closures
Creating inner functions
Calling inner functions from elsewhere
Understanding variable scope
Handling interactions between closures
Creating closures in jQuery
Passing arguments to $(document).ready()
Assigning event handlers
Binding handlers in loops
Giving names to functions
Handling memory-leak hazards
Avoiding accidental reference loops
Managing loops between the DOM and JavaScript
Disentangling reference loops with jQuery
Summary
B. Testing JavaScript with QUnit
Downloading QUnit
Setting up the document
Organizing tests
Adding and running tests
Asynchronous testing
Other types of tests
Practical considerations
Further reading
Summary
C. Quick Reference
Selector expressions
Simple CSS
Position among siblings
Position among matched elements
Attributes
Forms
Miscellaneous selectors
DOM traversal methods
Filtering
Descendants
Siblings
Ancestors
Collection manipulation
Working with selected elements
Event methods
Binding
Shorthand binding
Triggering
Shorthand triggering
Utility
Effect methods
Predefined effects
Custom animations
Queue manipulation
DOM manipulation methods
Attributes and properties
Content
CSS
Dimensions
Insertion
Replacement
Removal
Copying
Data
Ajax methods
Issuing requests
Request monitoring
Configuration
Utilities
Deferred objects
Object creation
Methods of deferred objects
Methods of promise objects
Miscellaneous properties and functions
Properties of the jQuery object
Arrays and objects
Object introspection
Other
Index
Learning jQuery Fourth Edition
Learning jQuery Fourth Edition
Copyright © 2013 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 edition : July 2007
Second published: Feburary 2009
Third published: September 2011
Fourth published: June 2013
Production Reference: 1180613
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-314-5
www.packtpub.com
Cover Image by Karl Swedberg (<kswedberg@gmail.com>)
Credits
Authors
Jonathan Chaffer
Karl Swedberg
Reviewers
Kaiser Ahmed
Carlos Estebes
Alex Libby
Natalie MacLees
Acquisition Editor
Rukhsana Khambatta
Lead Technical Editor
Dayan Hyames
Technical Editors
Veena Pagare
Zafeer Rais
Kaustubh S. Mayekar
Project Coordinator
Leena Purkait
Proofreader
Paul Hindle
Indexer
Monica Ajmera Mehta
Graphics
Ronak Dhruv
Abhinash Sahu
Production Coordinator
Aditi Gajjar
Cover Work
Aditi Gajjar
Foreword
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 since 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 of 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 in 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: 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. But 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 through the experience of getting to know jQuery better.
For me, jQuery is much more than a block of code. It's the sum of total experiences that have transpired over the years in order to make the library happen. The considerable ups and downs and 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 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 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
About the Authors
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, he 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 also responsible for major overhauls of Drupal's menu system and developer API reference.
He 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, he is responsible for maintaining the jQuery API site at api.jquery.com. He is also a member of jQuery's Board of Advisors and a presenter at workshops and conferences. When he isn't coding, he likes to hang out with his family, roast coffee in his garage, and exercise at the local CrossFit 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. Bryan, Steve, and Jack have supported me and given me a paycheck for the past five years, and for that I am truly grateful.
Many thanks to John Resig for creating the world's greatest JavaScript library and to Dave Methvin and the core developer team for taking up the torch.
About the Reviewers
Alex Libby works in IT support. He has been involved in supporting end users for the last 15 years in a variety of different environments and currently works as a Technical Analyst supporting a medium-sized SharePoint estate for an international parts distributor based in the U.K. Although Alex gets to play with different technologies in his day job, his first true love has always been with the open source movement, and in particular experimenting with CSS3, HTML5, and jQuery. To date, Alex has written several books for Packt Publishing, including one on HTML5 Video and another on jQuery Tools.
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 and methodologies. He has over 10 years of web development experience and holds a B.Sc. in Computer Science from California State University, Los Angeles.
He previously collaborated with Packt Publishing as a technical reviewer in the third edition of Learning jQuery and jQuery Hotshot.
Kaiser Ahmed is a professional web developer. He gained his B.Sc. from Khulna University of Engineering and Technology (KUET) and M.Sc. in Computer Science and Engineering from United International University, Dhaka. He is also a co-founder of CyberXpress.Net Inc. (www.cyberxpress.net) based in Bangladesh.
He has been working as a Senior Software Developer at Krembo Interactive and D1SH.COM CORP., Canada, for the last 2 years.
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 toolsets (PHP, MySQL, Apache, Linux, and others (that is, LAMP), frontend development with CSS and HTML/XHTML.
I want to thank my loving wife, Maria Akther, for her great support.
Natalie MacLees is a frontend web developer and UI designer, and is the founder and principal of the interactive agency Purple Pen Productions. In 2012, she published jQuery for Designers with Packt Publishing. She founded and runs the jQuery LA Users' Group, and together with Noel Saw, she heads up the Southern California WordPress User's Group, organizing WordPress meetups, help sessions, and workshops. She makes her online home at nataliemac.com.
www.PacktPub.com
Support files, eBooks, discount offers and more
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
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.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
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.
Preface
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. Rapidly over the 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 has since stepped down from his role as lead developer of the project, jQuery has blossomed, in true open source fashion, to the point where it now boasts a top-notch core team headed by Dave Methvin, as well as a vibrant community of thousands of additional JavaScript 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 Fourth 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.
What this book covers
Chapter 1, Getting Started, will 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.
Chapter 2, Selecting Elements, will teach 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.
Chapter 3, Handling Events, will walk you through 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.
Chapter 4, Styling and Animating, will introduce you to jQuery's animation techniques and how to hide, show, and move page elements with effects that are both useful and pleasing to the eye.
Chapter 5, Manipulating the DOM, will teach you how to change your page on command. This chapter will also teach you how to alter the very structure of an HTML document, as well as adding to its content on the fly.
Chapter 6, Sending Data with Ajax, will walk you through 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.
Chapter 7, Using Plugins, will show you how to find, install, and use plugins, including the powerful jQuery UI and jQuery Mobile plugin libraries.
Chapter 8, Developing Plugins, will teach you 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.
Chapter 9, Advanced Selectors and Traversing, will 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.
Chapter 10, Advanced Events, will 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.
Chapter 11, Advanced Effects, will fine-tune the visual effects of jQuery that can be provided 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.
Chapter 12, Advanced DOM Manipulation, will provide you with 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.
Chapter 13, Advanced Ajax, will help you achieve a greater understanding of Ajax transactions, including the jQuery deferred object system for handling data that may become available at a later time.
Appendix A, JavaScript Closures, will help you gain a solid understanding of closures in JavaScript—what they are and how you can use them to your advantage.
Appendix B, Testing JavaScript with QUnit, will teach you 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.
Appendix C, Quick Reference, will provide 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.
What you need for this book
In order to run the example code demonstrated in this book, you need a modern web browser such as Google Chrome, Mozilla Firefox, Apple Safari, or Microsoft Internet Explorer.
To experiment with the examples and to work on the chapter-ending exercises, you will also need:
A basic text editor
Web development tools for the browser such as the Chrome Developer Tools or Firebug (as described in the Using development tools section of Chapter 1, Getting Started )
The full code package for each chapter, which includes a copy of the jQuery library (seen in the following Downloading the example code section)
Additionally, to run some of the Ajax examples in Chapter 6, Sending Data with Ajax and beyond, you will need a PHP-enabled web server.
Who this book is for
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. Prior knowledge of jQuery is not 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.10.x and jQuery 2.0.x, the latest versions at the time of writing.
Conventions
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: In addition, we can interact with this console directly from our code, using the console.log() method.
A block of code is set as follows:
$(document).ready(function() {
$('div.poem-stanza').addClass('highlight');
});
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
$('#switcher-narrow').bind('click', function() { $('body').removeClass().addClass('narrow');
});
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.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
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 <feedback@packtpub.com>, and mention the book title via the subject of your message.
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.
Customer support
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.
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.
In addition, the examples can be viewed in an interactive browser at http://book.learningjquery.com/.
Errata
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/submit-errata, 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
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 <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Getting Started
Today's World Wide Web (WWW) is a dynamic environment and its users set a high bar for both the style and function of sites. To build interesting and interactive sites, developers are turning to JavaScript libraries such as jQuery to automate common tasks and to simplify complicated ones. One reason the jQuery library is a popular choice 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, since many 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.
In this chapter, we will cover:
The primary features of jQuery
Setting up a jQuery code environment
A simple working jQuery script example
Reasons to choose the jQuery approach over plain JavaScript code
Common JavaScript development tools
What jQuery does
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 the 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:
Access elements in a document: Without a JavaScript library, web developers often need to write many lines of code to traverse the Document Object Model (DOM) tree and locate specific portions of an HTML document's structure. With jQuery, developers have a robust and efficient selector mechanism at their disposal, making it easy to retrieve the exact piece of the document that needs to be inspected or manipulated.
$('div.content').find('p');
Modify the appearance of a web page: CSS offers a powerful method of influencing the way a document is rendered, but it falls short when not all web browsers support the same standards. With jQuery, developers can bridge this gap, relying on the same standards support across all browsers In addition, jQuery can change the classes or individual style properties applied to a portion of the document even after the page has been rendered.
$('ul > li:first').addClass('active');
Alter the content of a document: Not limited to mere cosmetic changes, jQuery can modify the content of a document itself with a few keystrokes. Text can be changed, images can be inserted or swapped, lists