JQuery, JQuery UI, And JQuery Mobile: Recipes And Examples

Transcription

Praise for jQuery, jQuery UI, and jQuery Mobile“de Jonge and Dutson’s cookbook approach to jQuery, jQuery UI, and jQuery Mobileteaches how to create sophisticated projects quickly, removing all the guesswork. Theyreally make jQuery seem effortless!”—Joseph Annuzzi, Jr., Web architect, PeerDynamic.com“This book is great for all aspects of jQuery development; it has it all, from a great UIsection down to the most current tech, which is mobile. I found myself referencing thisbook numerous times for projects I am currently working on.“This book will be excellent for anyone who is eager to learn more about jQuery andwhat the capabilities are. The authors put the learning in terms that anyone can understand and build from.”—Erik Levanger, UI UX engineer“I have often said that when it comes to jQuery, half the battle is just being familiar withthe types of things it is capable of doing. Having a good foundation can easily help youbridge the gap between ‘This is going to be complicated’ and ‘I can do that with jQuery!’Like any good recipe book, this book includes ready-to-use code samples that demonstrate basic to advanced techniques. In addition to the major areas noted in thebook title, there are references on how to customize the jQuery UI features to meet yourneeds and bonus sections about creating and using plugins. I also really appreciate theauthors’ insights regarding performance issues and best practices. Lastly, speaking as someone with no previous jQuery Mobile experience, this book provides solid examplesto get you up and running fast. Overall, this book will help to greatly expand the skillsin your jQuery arsenal.”—Ryan Minnick, software developer, Verizon Wireless“The ultimate cookbook for anyone using jQuery, jQuery UI, or jQuery Mobile.”—Stretch Nate, Web applications developer, HealthPlan Services“Through easy-to-understand recipes, de Jonge and Dutson give the reader a practicalintroduction to all things jQuery, from the most basic selectors to advanced topics, suchas plugin authoring and jQuery Mobile. A great starting point for anyone interested inone of the most powerful JavaScript libraries.”—Jacob Seidelin, Web developer, Nihilogic

This page intentionally left blank

jQuery, jQuery UI,and jQuery Mobile

  Developer’s Library SeriesVisit developers-library.com for a complete list of available productsThe Developer’s Library Series from Addison-Wesley providespracticing programmers with unique, high-quality references andtutorials on the latest programming languages and technologies theyuse in their daily work. All books in the Developer’s Library are written byexpert technology practitioners who are exceptionally skilled at organizingand presenting information in a way that’s useful for other programmers.Developer’s Library books cover a wide range of topics, from opensource programming languages and databases, Linux programming,Microsoft, and Java, to Web development, social networking platforms,Mac/iPhone programming, and Android programming.

jQuery, jQuery UI,and jQuery MobileRecipes and ExamplesAdriaan de JongePhil DutsonUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.Editor-in-ChiefMark TaubThe authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connectionwith or arising out of the use of the information or programs contained herein.Development EditorSheri CainThe publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom coversand content particular to your business, training goals, marketing focus, and branding interests. For more information, please contactU.S. Corporate and Government Sales(800) 382-3419corpsales@pearsontechgroup.comFor sales outside the United States, please contactInternational Salesinternational@pearsoned.comVisit us on the Web: informit.com/awCataloging-in-Publication Data is on file with the Library of Congress.Copyright 2013 Pearson Education, Inc.All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means,electronic, mechanical, photocopying, recording, or likewise. To obtain permission to usematerial from this work, please submit a written request to Pearson Education, Inc.,Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or youmay fax your request to (201) 236-3290.ISBN-13: 978-0-321-82208-6ISBN-10:      0-321-82208-0Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.First printing, November 2012Acquisitions EditorLaura LewinManaging EditorJohn FullerFull-ServiceProductionManagerJulie B. NahilCopy EditorOctal Publishing,Inc.IndexerTed LauxProofreaderDiana CoeTechnicalReviewersJoseph AnnuzziJacob SeidelinEditorial AssistantOlivia BasegioCover DesignerChuti PrasertsithCompositorLaurelTech

To my loving and supportive girlfriend, Christine Kam.—AdriaanTo my mom, who taught me to love books; my dad, whotaught me to love technology; and my family, who supportsmy indulgence of both.—Phil

This page intentionally left blank

Contents at a GlancePreface xixAcknowledgments xxiiiAbout the Author xxvI: Core11 Getting Started with jQuery2 Selecting Elements273 Modifying the Page4134 Listening and Responding to Events5 Communicating with the ServerII: UI65811016 Interacting with the User1037 Interacting with Widgets135III: Mobile1838 Changing the Look and Feel1859 Navigating Pages by Using jQuery Mobile10 Interacting with jQuery MobileIV: Plugins24929111 Creating Plugins29312 Working with Third-Party PluginsIndex 351323203

This page intentionally left blank

ContentsPrefacexixAcknowledgmentsxxiiiAbout the Author xxvI: Core11 Getting Started with jQuery 3Recipe: Introducing the Basic Usage of jQuery 3Recipe: Using jQuery with Other Libraries 6Recipe: Determining the jQuery Version 7Recipe: Iterating Arrays with each()8Recipe: Manipulating Arrays by Using map() 9Recipe: Working with Arrays of Elements 10Recipe: Getting the Position of an Element by Usingindex() 12Recipe: Finding Elements in an Array by Usinggrep() 13Recipe: Determining the Size of an Element Set byUsing length() 14Recipe: Retrieving HTML5 data- Attributes 15Recipe: Storing Element Data by Using data()16Recipe: Removing Element Data by UsingremoveData() 18Recipe: Testing and Manipulating Variables 19Recipe: Extending Objects by Using extend()Recipe: Serializing the Data in a Form24Recipe: Testing Browsers for Feature SupportSummary2225262 Selecting Elements 27Recipe: Combining Two ElementSets by Using add() 27Recipe: Refining the Selection by Using filter() 28Recipe: Selecting Descendants byUsing find() and children() 29

xiiContentsRecipe: Selecting Elements by Usinghas() and Testing by Using is() 31Recipe: Selecting Form Elements byUsing Pseudo-Selectors 32Recipe: Nesting Selectors 33Recipe: Emulating a CSS Hover Selector 34Recipe: Selecting on Text by Using contains() 35Example: Highlighting a Single Word 36Recipe: Creating Custom Selectors 37Recipe: Scoping the Selection Context 39Summary 403 Modifying the Page41Recipe: Adding Classes 41Example: Removing Classes 42Recipe: Generating Class Names 43Recipe: Changing Properties and Attributes 45Recipe: Changing the HTML Containedwithin an Element 46Recipe: Adding Content by Using append()and appendTo() 48Example: Appending the Outcome of a Function 49Recipe: Adding Content by Using prepend()and prependTo() 50Recipe: Generating HTML Dynamicallyby Using jQuery 51Recipe: Attaching and Detaching Elements 53Recipe: Copying Elements by Using clone() 54Recipe: Inserting Elements at Specific Positions 56Example: Moving Items Up and Down the List 58Recipe: Removing Elements 60Recipe: Wrapping and Unwrapping Elements 61Summary 644 Listening and Responding to Events 65Recipe: Listening to Mouse Events 65Example: Drawing on a Canvas 67Recipe: Listening to Keyboard Events 69Recipe: Listening to Form Events 70

ContentsRecipe: Listening to Scroll Events 72Recipe: Adding Central Event Listeners by Using live()and die() 73Recipe: Delegating Events to Specific Ancestor Elementsby Using delegate() 75Recipe: Changing the Execution Context of a Function byUsing proxy() 78Summary805 Communicating with the Server 81Recipe: Setting Up an Example Server in Node.js 81Recipe: Performing a GET Request83Recipe: Loading HTML Directly 85Recipe: Handling the Result by Using Promises 86Recipe: Handling Server Errors 87Recipe: Catching Page-not-Found Results 89Recipe: Handling Page Redirects 90Recipe: Setting Request Timeouts 91Recipe: Passing HTTP Headers 93Example: Validating Form Input on theServer Side 94Recipe: Loading XML 96Recipe: Listening to AJAX Events 97Recipe: Reading JSONP from an External Server 98Summary100II: UI 1016 Interacting with the User 103Downloading and Installing jQuery UI 103Recipe: Dragging Elements 104Styling the Draggable Element 105Setting Draggable Options 105Catching Draggable Events 109Invoking Methods on Draggable 111Recipe: Dropping Elements 111Styling the Droppable Element 113Setting Droppable Options 113xiii

xivContentsCatching Droppable Events 114Invoking Methods on Droppable 115Recipe: Changing the Order of Elements by UsingSortable 116Styling a Sortable 117Setting Sortable Options 117Catching Events on Sortable 118Invoking Methods on Sortable 122Example: Sorting Elements in a Tree Structure 123Recipe: Selecting Elements in an Unordered List 124Styling Selectable Elements 126Setting Selectable Options 126Catching Events on Selectable 126Invoking Methods on Selectable 128Example: Selecting Elements in a Tree Structure 128Recipe: Resizing Elements 130Styling the Resizable Element 131Setting Resizable Options 131Catching Events on Resizable 133Invoking Methods on Resizable 134Summary1347 Interacting with Widgets135Recipe: Grouping Content by Using the Accordion 135Styling the Accordion 136Setting Accordion Options 137Catching Events on Accordion 139Methods 141Recipe: Suggesting Input Values by UsingAutocomplete 142Styling the Autocomplete Component 143Setting Autocomplete Options 144Catching Events on Autocomplete 145Invoking Methods on Autocomplete 147Recipe: Transforming Elements into Buttons 147Styling Buttons 149Setting Button Options 149

ContentsCatching Events on Buttons150Methods 150Example: Styling Radio Buttons by Using aButtonset 151Recipe: Choosing Dates by Using the Datepicker 152Styling the Datepicker 152Setting Datepicker Options 154Catching Events on Datepicker 158Invoking Methods on the Datepicker 160Recipe: Attracting Attention with the Dialog 160Styling the Dialog161Setting Dialog Options 162Catching Events on the Dialog 164Invoking Methods on the Dialog 167Recipe: Displaying Status of a Process by Using theProgressbar 168Styling the Progressbar 169Setting Progressbar Options 169Catching Progressbar Events 169Invoking Methods on the Progressbar 170Recipe: Retrieving Numbers by Using a Slider 170Styling the Slider Element 172Setting Slider Options 172Catching Slider Events 173Invoking Methods on the Slider 174Recipe: Navigating a Page by Using Tabs174Styling the Tab Element 176Setting Options on the Tabs Widget 177Catching Events on the Tabs Component 178Invoking Methods on the Tabs Component 180Summary181III: Mobile 1838 Changing the Look and Feel 185Changing the Styling of jQuery UI Components 185Creating Animations by Using jQuery Core 186xv

xviContentsRecipe: Animating Colors by Using jQuery UI187Recipe: Hiding Elements by Using Fade and Slide injQuery Core 189Recipe: Adding Graphical Effects by UsingjQuery UI 191Recipe: Animating Addition and Removal of CSSClasses by Using jQuery UI 192Recipe: Displaying all Easing Functions in jQuery UI asCharts 194Recipe: Displaying All Icons in jQuery UI196Recipe: Executing Code at the End of an Animation witha Promise 198Recipe: Executing Code Within Animations by UsingQueue and Dequeue 200Summary 2029 Navigating Pages by Using jQuery Mobile 203Recipe: Setting Up jQuery Mobile Basics 203Recipe: Serving Multiple Pages from aSingle HTML File 205Recipe: Changing the Title Element 206Recipe: Loading External Pages Using AJAX 208Recipe: Displaying Page Loading Messages 210Recipe: Linking to External Pages without AJAX 212Recipe: Specifying the Transition Animation 213Recipe: Specifying Custom Transition Animations 214Recipe: Listening to Mobile Events 217Recipe: Generating Back Buttons 221Recipe: Adding Footers to the Bottomof the Page 223Recipe: Fixing the Footer Across Pages 225Recipe: Keeping the Footer in a Fixed Position 227Recipe: Hiding and Showing the Footer 229Recipe: Optimizing Headers and Footers forFullscreen View 231Recipe: Changing Color Schemes with Themes 232Recipe: Using Multiple Columns 234Recipe: Changing Pages by Using JavaScript Calls 236Recipe: Loading Pages by Using JavaScript Calls 239

ContentsRecipe: Attaching Data to DOM Nodes in jQueryMobile 241Recipe: Utilizing jQuery Mobile Helper Functions 242Summary24610 Interacting with jQuery Mobile 249Recipe: Displaying Toolbars Inline in Content 249Recipe: Displaying a Warning Bar 250Recipe: Adding Menu Bars to Footer Elements 252Recipe: Navigating with a Navigation Bar253Recipe: Showing and Hiding Elements byUsing Collapsible 257Recipe: Adding Accordion Behavior by UsingCollapsible Sets 258Recipe: Acquiring Basic Text Input by Using FormFields 260Recipe: Acquiring Calendar-Based Input 261Recipe: Displaying Input Fields by Using AlternativeKeyboards 263Recipe: Displaying Specialized Input Fields 265Recipe: Acquiring Integers by Using Sliders 267Recipe: Setting Binaries with Flip Switches 268Recipe: Selecting a Single Element by Using RadioButtons 269Recipe: Selecting Multiple Elements by Using CheckBoxes 271Recipe: Selecting Elements from Drop-Down Lists 273Recipe: Displaying Native Forms by Using jQueryMobile Off 276Recipe: Displaying Lists of Elements 278Recipe: Filtering List Elements 286Recipe: Grouping Form Elements in Lists 288SummaryIV: Plugins28929111 Creating Plugins 293Recipe: Setting Up a Simple Static Plugin 293Recipe: Creating Simple Context-Aware Plugins 295xvii

xviiiContentsRecipe: Chaining jQuery Functions and Plugins 296Recipe: Parameterizing Plugins 297Recipe: Providing Default Parameters 299Recipe: Operating the Plugin by Using Methods 300Recipe: Creating a Plugin that Creates Plugins 303Recipe: Registering and Invoking CallbackFunctions 306Recipe: Passing Context to Callback Functions 308Recipe: Returning Deferred Objects to Call SeparateCallbacks on Success and on Error 309Recipe: Returning a Promise to Protect Internals 311Recipe: Demonstrating the Promise(d) Protection 312Recipe: Using Promise to Control Flow Structures 314Recipe: Visualizing Progress Before the FinalCallback 315Recipe: Providing Context to Callback Functions 317Recipe: Providing a Context to Progress Functions 319Summary 32012 Working with Third-Party Plugins323Recipe: Displaying a Modal 323Recipe: Using a Drop-Down Menu 326Recipe: Using ScrollSpy 328Recipe: Toggling Tabs 331Recipe: Adding Tooltips 333Recipe: Adding a Popover 334Recipe: Alerting the User 336Recipe: Button Control 338Recipe: Collapsing Content 341Recipe: Putting Content in a Carousel 344Recipe: Using typeahead for Autocomplete 347SummaryIndex349351

PrefaceWhen JavaScript first hit the Internet scene, it was quickly disregarded by experts as atoy suitable for diversion and useless for user interaction. Today, it is the driving force thathelps create rich user interfaces, seamless data integration, and client-side support.Although everything is possible using plain JavaScript, many have discovered the useof various libraries and frameworks to help them do more. jQuery is the perfect libraryto fill the need for JavaScript integration. The motto of jQuery is write less, do more. This issomething the jQuery team takes very seriously. Whether you are working on a standarddesktop site that needs a little DOM modification, or you’re adding your own custom setof controls, or even if you’re handling mobile devices, the jQuery team has a library thathas been handcrafted and tested on as many platforms, browsers, and devices as possibleto ensure the very best experience for both the developer and the user.Why a Recipe and Example Book on jQuery?Some have been quick to say that if you know CSS, you know how to use jQuery, butthis isn’t entirely true. Although having this knowledge certainly helps one to understandthe selector engine in jQuery, there are so many extra functions to help manipulate, calculate, and add interaction to your site that a book is simply a must-have to ensurethat you are aware of the amazing things that jQuery can do. A recipe and example bookis essential because it not only informs you about the functions that you can use, but italso gives you self-contained examples that work with quick explanations to point outthe tricky parts or confusing areas.The inclusion of the jQuery UI and jQuery Mobile libraries makes this book a superior reference guide; now you can easily learn about the other libraries that thejQuery team has made and see how they can fit together to make your next project aseamless, crowd-pleasing success.Who This Book Is ForThose who have a working knowledge of HTML, CSS, and basic JavaScript shouldfeel at home picking this book up and starting to work through the examples. Those notfamiliar with Web development might need a little extra time to get up to speed withwhat is presented here. That having been said, those who learn well by seeing the fullHTML page layout with the required script to make the example run will learn quicklyand  efficiently.

xxPrefaceHow to Use This BookEach recipe and example is a set of self-contained scripts that can be loaded onto yourfavorite Web server and accessed from your browser. Although it is possible to run someof the examples by dropping or loading the example code directly in your browser, anyexamples that use AJAX will fail, so using a Web server is highly recommended.When finished reading this book, you shouldBe comfortable adding jQuery to your Web projectsUnderstand the differences among jQuery core, jQuery UI, and jQuery MobileBe familiar with the basic functionality and functions of jQuery coreBe proficient adding styles and widgets, and interacting with the user throughjQuery core and jQuery UIBe able to create a mobile site by using the jQuery Mobile libraryBe comfortable creating your own plugin and incorporating it into your siteBe able to add third-party plugins such as those from the Twitter Bootstrap frameworknnnnnnnnnnnnnnBook StructureChapters 1 through 5 cover the jQuery core library. Chapter 1 gives an introductionto the basic usage and how to include jQuery along with setting up arrays, using dataattributes, and testing browser feature support. Chapter 2 covers how to fine-tune yourelement selection from the DOM. Chapter 3 teaches how jQuery can help manipulatethe DOM structure of your site. Chapter 4 takes a tour of event handling with jQueryand covers the difference between binding in jQuery versions 1.6 and 1.7. Chapter 5shows you how to communicate with a Web server, including working with AJAX, pageerrors, page redirects, and XML.Chapters 6 through 8 cover the usage of the jQuery UI library. Chapter 6 demonstrates the additional functionality that jQuery UI brings, such as draggable, droppable, and sortable objects. Chapter 7 covers using the widgets, including accordions,auto-complete, buttons, date pickers, dialogs, progress bars, sliders, and tab components.Chapter 8 takes on the styles and theme of the jQuery UI along with effects and transitions.Chapters 9 and 10 give a course on using the jQuery Mobile library. Chapter 9 startswith the basics of setting up a mobile site and covers page structure, page loading, andpage transition and animation. Chapter 10 covers the additional widgets and styles thatjQuery Mobile provides, including navigation bars, sliders, flip switches, and form elements.Chapters 11 and 12 cover the use of plugins. Chapter 11 provides a comprehensiveoverview of what a plugin consists of and how to create your own with method handlingand function chaining. Chapter 12 gives examples of using trusted third-party pluginsfrom the Twitter Bootstrap framework to add extra functionality and style to your  project.

PrefaceAdditional ResourcesThere are many places that you can learn more about jQuery, jQuery UI, and jQueryMobile. The official sites themselves offer excellent documentation and explain thechoices behind deprecating code and give hints and warnings about upcoming features.Here are some helpful sites that you should visit:jQuery API docs: http://api.jquery.com/jQuery UI docs: http://jqueryui.com/demos/jQuery Mobile docs: http://jquerymobile.com/demos/Twitter Bootstrap JavaScript docs: lZurb Foundation docs: http://foundation.zurb.com/docs/jQuery Tools: http://jquerytools.org/Stack Overflow forums: http://stackoverflow.com/nnnnnnnnnnnnnnxxi

This page intentionally left blank

AcknowledgmentsFirst of all, I would like to thank Phil Dutson for joining this book project and helpingto finish it before the deadline. In addition to Laura Lewin, Olivia Basegio, Sheri Cain,Jacob Seidelin, and Joseph Annuzzi—as mentioned by Phil—I would also like to thankTrina MacDonald, who started this book project at Pearson.I would like to say thanks to my colleagues, both at my former employer, ANWB, andmy new employer, Xebia, for giving me inspiration and great ideas. I love working withpeople who share the same interest in new technologies!I am thankful for my family and friends who encourage me wherever I go. And inparticular, I am happy and blessed with my girlfriend, Christine Kam. Thank you for yourunconditional support!—AdriaanI’d like to thank Adriaan de Jonge who started this project and was gracious enoughto allow me to help him finish it. I also want to recognize all of the hard work andcountless hours put into this project by the amazing team at Pearson. Thanks go to LauraLewin who brought me onto the project; Olivia Basegio for coordinating everything;Sheri Cain for correcting the flow and helping structure the visual representation of thematerial; my absolutely brilliant tech editors Joseph Annuzzi and Jacob Seidelin, who notonly made sure that the code runs properly, but that the explanations about why it runswere clear and accurate. Thanks also go to Bob Russell of Octal Publishing, Inc., for hiscommendable copyediting prowess and Julie Nahil at Pearson for all of the coordinationduring the production process.I also want to thank my designer friends from UltraCube (Alan Lawrence, Jake Stuart,Candis Sorenson, Kaylee White, and Jen Lewis) who constantly remind me that life iswhatever you make of it, and my current e-commerce team (Tracy Cox, Brett Wood,Ryan Jensen, Remo Galli, Eric Barnett, and Chris Lewis) who remind me to alwaysmake sure you are doing the things you love.—Phil

This page intentionally left blank

About the AuthorsAdriaan de Jonge works as a Consultant for Xebia IT Architects in The Netherlands.Adriaan specializes in Internet, content management, and Java. He is interested in newtechnologies such as MongoDB, Node.js, HTML5, and various cloud-computing platforms. Adriaan is also the author of Essential App Engine (Addison-Wesley, 2012) andseveral articles for IBM developerWorks on Java, XML, and Internet technologies. He hasexperience as a conference speaker at JFall 2011 and the Scandinavian DeveloperConference in 2012.Phil Dutson is the lead front-end developer for ICON Health and Fitness. He hasworked on projects and solutions for NordicTrack, ProForm, Freemotion, Sears, Costco,Sam’s Club, and others. He was an original team member of the iFit team that integratedGoogle Maps into personalized workout creation and playback. Phil co-founded and currently manages The E-Com DevBlog, a development blog focused on Web development and solutions. To learn more visit http://dev.tonic1394.com. He is also theauthor of Sams Teach Yourself jQuery Mobile in 24 Hours (Sams, 2013).

This page intentionally left blank

Chapter 5Communicating withthe ServerThis chapter discusses how to communicate with the server. To demonstrate this, a simpletest server is written in Node.js, which is a server-side JavaScript execution environment.After that, various recipes show how to get JSON, HTML, XML, and JSONP from theserver by using AJAX methods and functions. This chapter pays a lot of attention to errorhandling to assure the quality of the end result.Recipe: Setting Up an Example Server in Node.jsTo test the AJAX examples, you need a server. For the examples, it does not matterwhether the server is written in PHP, Python, Ruby, Erlang, Dart, Go, .Net, or Java. Keepin mind, of course, that all servers take some setup time.Because jQuery is JavaScript, this book assumes that you are already familiar with it.That is why the test server is provided in JavaScript code. To run the code, you need todownload and install Node.js at http://nodejs.org.There are no plugins or further modules needed for this example. For reference, thecode in this chapter was developed and tested by using versions 0.4.11 and 0.6.19 ofNode.js. After installing Node.js and putting the example in a file called 01-app.js, youcan run the code from the following command line:node 01-app.jsIf this command does not start your node server, ensure that you have correctly addedthe node to your system path. When running the code, you can access subsequent examples at http://localhost:1337/02-ajax-get.html.Listing 5.1 contains the implementation for the Node.js test server.

82Chapter 5 Communicating with the ServerListing 5.1L istening for HTTP Requests Generated by Recipes in This Chapter andResponding Accordingly00 var http require('http'),01       url require('url'),02       fs require('fs');03 http.createServer(function (req, res) {04        var reqData �  url: url.parse(req.url,     method: ��     headers: req.headers },08        path f(path.match(/ \/[0-9a-z\-] \.(html) (json) (xml)    fs.readFile('.' path, function (err, data) �            if (err) ��     res.writeHead(404, {'Content-Type': �          res.end('not �          else ��     if(path.split('.')[1]  res.writeHead(200, {'Content-Type':           else if(path.split('.')[1] ��res.writeHead(200, {'Content-Type': 200, {'Content-Type': ��       else if(path '/return-http-headers') �  res.writeHead(200, {'Content-Type': �    else if(path '/sleep') �  var endTime new Date().getTime() ��   while (new Date().getTime()      res.writeHead(500, {'Content-Type':        res.end('slow ��    else if(path '/validate') �  var keys    for(var key in reqData.url.query) uery[key] iteHead(200, {'Content-Type': keys));

Recipe: Performing a GET RequestListing 5.1L istening for HTTP Requests Generated by Recipes in This Chapter andResponding Accordingly ��    else if(path '/redirect') �  res.writeHead(302, �           'Location': '/test-values.json' �       else if(path '/fail\-on\-purpose') �  res.writeHead(500, {'Content-Type':        res.end('unexpected" ��   else �  res.writeHead(404, {'Content-Type':        res.end('not found');57        }58 }).listen(1337, "localhost");59 console.log('Server running at http://localhost:1337/');HTML, JSON, and XML requests are passed to the file server. Some special cases youwill encounter in the following recipes are handled each with their own specific response.Given the requested path, the responses should not be too surprising.If the file cannot be found, or there is no handler and the request is not XML, JSON,or HTML, a 404 err

"The ultimate cookbook for anyone using jQuery, jQuery UI, or jQuery Mobile." —Stretch Nate, Web applications developer, HealthPlan Services "Through easy-to-understand recipes, de Jonge and Dutson give the reader a practical introduction to all things jQuery, from the most basic selectors to advanced topics, such