Jquery in Action
Total Page:16
File Type:pdf, Size:1020Kb
THIRD EDITION IN ACTION Bear Bibeault Yehuda Katz Aurelio De Rosa FOREWORDS BY Dave Methvin John Resig MANNING www.EBooksWorld.ir Praise for Earlier Editions of jQuery in Action Every technical book should be like this one…concise but clear, humorous but not silly, and one that answers all the questions it raises, quickly. The reader is never left wondering “But what about...” for more than a sentence or two. —JRoller Online Book Reviews Thanks to the authors and their exemplary style, this comprehensive book, or operating manual as it might be called, can be taken in a front-to-back approach to learn from scratch, or as a ref- erence for those already dabbling in jQuery and needing verification of best practices. —Matthew McCullough Denver Open Source Users Group With its capable technical coverage, extensive use of sample code, and approachable style, this book is a valuable resource for any web developer seeking to maximize the power of JavaScript, and a must-have for anyone interested in learning jQuery. —Michael J. Ross Web Developer and Slashdot Contributor An excellent work, a worthy successor to others in Manning’s In Action series. It is highly read- able and chock-full of working code. The Lab Pages are a marvelous way to explore the library, which should become an important part of every web developer’s arsenal. Five stars all ‘round! —David Sills JavaLobby, DZone I highly recommend the book for learning the fundamentals of jQuery and then serving as a good reference book as you leverage the power of jQuery more and more in your daily development. —David Hayden MVP C#, Codebetter.com I highly recommend this book to any novice or advanced JavaScript developers who want to get serious about JavaScript and start writing optimized and elegant code without all the hassle of traditional JavaScript code authoring. —Val’s Blog The Elements of Style for JavaScript. —Joshua Heyer Trane Inc. www.EBooksWorld.ir www.EBooksWorld.ir jQuery in Action THIRD EDITION BEAR BIBEAULT YEHUDA KATZ AURELIO DE ROSA MANNING Shelter Island www.EBooksWorld.ir For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2015 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editors: Jeff Bleiel, Sean Dennis 20 Baldwin Road Technical development editor: Al Scherer PO Box 761 Copyeditor: Linda Recktenwald Shelter Island, NY 11964 Proofreader: Melody Dolab Technical proofreader: Richard Scott-Robinson Typesetter: Dottie Marsico Cover designer: Marija Tudor ISBN 9781617292071 Printed in the United States of America 12345678910–EBM–201918171615 www.EBooksWorld.ir To Annarita, because you give balance to my life —Aurelio www.EBooksWorld.ir www.EBooksWorld.ir brief contents PART 1 STARTING WITH JQUERY............................................... 1 1 ■ Introducing jQuery 3 PART 2 CORE JQUERY.............................................................21 2 ■ Selecting elements 23 3 ■ Operating on a jQuery collection 52 4 ■ Working with properties, attributes, and data 79 5 ■ Bringing pages to life with jQuery 99 6 ■ Events are where it happens! 134 7 ■ Demo: DVD discs locator 172 8 ■ Energizing pages with animations and effects 188 9 ■ Beyond the DOM with jQuery utility functions 224 10 ■ Talk to the server with Ajax 260 11 ■ Demo: an Ajax-powered contact form 301 PART 3 ADVANCED TOPICS ....................................................317 12 ■ When jQuery is not enough...plugins to the rescue! 319 13 ■ Avoiding the callback hell with Deferred 358 14 ■ Unit testing with QUnit 385 15 ■ How jQuery fits into large projects 412 vii www.EBooksWorld.ir www.EBooksWorld.ir contents foreword to the third edition xvii foreword to the first edition xix preface xxi acknowledgments xxiii about this book xxv about the authors xxix PART 1 STARTING WITH JQUERY...................................... 1 Introducing jQuery 3 1 1.1 Write less, do more 4 1.2 Unobtrusive JavaScript 6 Separating behavior from structure 7 ■ Segregating the script 7 1.3 Installing jQuery 8 Choosing the right version 9 ■ Improving performances using a CDN 11 1.4 How jQuery is structured 13 Save space creating your own custom build 14 1.5 jQuery fundamentals 15 Properties, utilities, and methods 15 ■ The jQuery object 15 The document ready handler 17 ■ Summary 19 ix www.EBooksWorld.ir x CONTENTS PART 2 CORE JQUERY ....................................................21 Selecting elements 23 2 2.1 Selecting elements for manipulation 24 2.2 Basic selectors 26 The All (or Universal) selector 27 ■ The ID selector 30 The Class selector 30 ■ The Element selector 31 2.3 Retrieving elements by their hierarchy 32 2.4 Selecting elements using attributes 34 2.5 Introducing filters 37 Position filters 38 ■ Child filters 39 ■ Form filters 42 Content filters 43 ■ Other filters 44 ■ How to create custom filters 46 2.6 Enhancing performances using context 49 2.7 Testing your skills with some exercises 50 Exercises 50 ■ Solutions 51 2.8 Summary 51 Operating on a jQuery collection 52 3 3.1 Generating new HTML 53 3.2 Managing the jQuery collection 55 Determining the size of a set 57 ■ Obtaining elements from a set 57 ■ Getting sets using relationships 62 Slicing and dicing a set 66 ■ Even more ways to use a set 75 3.3 Summary 77 Working with properties, attributes, and data 79 4 4.1 Defining element properties and attributes 80 4.2 Working with attributes 83 Fetching attribute values 83 ■ Setting attribute values 84 Removing attributes 86 ■ Fun with attributes 86 4.3 Manipulating element properties 88 4.4 Storing custom data on elements 91 4.5 Summary 98 www.EBooksWorld.ir CONTENTS xi Bringing pages to life with jQuery 99 5 5.1 Changing element styling 100 Adding and removing class names 100 ■ Getting and setting styles 104 5.2 Setting element content 114 Replacing HTML or text content 114 ■ Moving elements 116 Wrapping and unwrapping elements 122 ■ Removing elements 126 ■ Cloning elements 128 ■ Replacing elements 129 5.3 Dealing with form element values 131 5.4 Summary 133 Events are where it happens! 134 6 6.1 Understanding the browser event models 136 The DOM Level 0 Event Model 136 ■ The DOM Level 2 Event Model 143 ■ The Internet Explorer Model 148 6.2 The jQuery Event Model 149 Attaching event handlers with jQuery 149 ■ Removing event handlers 156 ■ Inspecting the Event instance 159 Triggering event handlers 160 ■ Shortcut methods 165 How to create custom events 168 ■ Namespacing events 169 6.3 Summary 170 Demo: DVD discs locator 172 7 7.1 Putting events (and more) to work 173 Filtering large data sets 174 ■ Element creation by template replication 176 ■ Setting up the mainline markup 178 Adding new filters 179 ■ Adding the controls templates 182 Removing unwanted filters and other tasks 183 ■ Showing the results 183 ■ There’s always room for improvement 186 7.2 Summary 187 Energizing pages with animations and effects 188 8 8.1 Showing and hiding elements 189 Implementing a collapsible “module” 190 ■ Toggling the display state of elements 192 www.EBooksWorld.ir xii CONTENTS 8.2 Animating the display state of elements 193 Showing and hiding elements gradually 193 ■ Introducing the jQuery Effects Lab Page 198 ■ Fading elements into and out of existence 200 ■ Sliding elements up and down 202 ■ Stopping animations 203 8.3 Adding more easing functions to jQuery 204 8.4 Creating custom animations 206 A custom scale animation 209 ■ A custom drop animation 210 A custom puff animation 211 8.5 Animations and queuing 213 Simultaneous animations 213 ■ Queuing functions for execution 215 ■ Inserting functions into the effects queue 221 8.6 Summary 222 Beyond the DOM with jQuery utility functions 224 9 9.1 Using the jQuery properties 225 Disabling animations 226 ■ Changing the animations rate 226 ■ The $.support property 227 9.2 Using other libraries with jQuery 228 9.3 Manipulating JavaScript objects and collections 232 Trimming strings 232 ■ Iterating through properties and collections 233 ■ Filtering arrays 235 ■ Translating arrays 237 ■ More fun with JavaScript arrays 239 Extending objects 242 ■ Serializing parameter values 244 Testing objects 248 ■ Parsing functions 251 9.4 Miscellaneous utility functions 254 Doing nothing 254 ■ Testing for containment 254 Prebinding function contexts 255 ■ Evaluating expressions 257 ■ Throwing exceptions 258 9.5 Summary 259 Talk to the server with Ajax 260 10 10.1 Brushing up on Ajax 261 Creating an