CuuDuongThanCong.com https://fb.com/tailieudientucntt Practical jQuery Mukund Chaudhary Ankur Kumar CuuDuongThanCong.com https://fb.com/tailieudientucntt Practical jQuery Copyright © 2015 by Mukund Chaudhary and Ankur Kumar This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law ISBN-13 (pbk): 978-1-4842-0788-8 ISBN-13 (electronic): 978-1-4842-0787-1 Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director: Welmoed Spahr Lead Editor: Louise Corrigan Technical Reviewer: Jose Dieguez Castro Editorial Board: Steve Anglin, Mark Beckner, Gary Cornell, Louise Corrigan, Jim DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing, Matt Wade, Steve Weiss Coordinating Editor: Jill Balzano Copy Editor: Michael G Laraque Compositor: Spi Global Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail ordersny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook CuuDuongThanCong.com https://fb.com/tailieudientucntt versions and licenses are also available for most titles For more information, reference our Special Bulk Sales– eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ CuuDuongThanCong.com https://fb.com/tailieudientucntt We would like to dedicate this book to all those who believe in honesty and hard work CuuDuongThanCong.com https://fb.com/tailieudientucntt Contents at a Glance About the Authors About the Technical Reviewer Acknowledgments Introduction Chapter 1: Evolution of jQuery Chapter 2: Getting Started with jQuery Chapter 3: Traversing DOM with jQuery Chapter 4: DOM Manipulation with jQuery Chapter 5: Events in jQuery Chapter 6: Real World Events in jQuery Chapter 7: Animation in jQuery Chapter 8: Ajax with jQuery Chapter 9: Creating Plug-ins with jQuery Chapter 10: Integrating Plug-ins with jQuery Chapter 11: Using jQuery Frameworks Chapter 12: Testing jQuery with QUnit Index CuuDuongThanCong.com https://fb.com/tailieudientucntt Contents About the Authors About the Technical Reviewer Acknowledgments Introduction Chapter 1: Evolution of jQuery Traditional JavaScript Basics The Window Object Child Objects Old School Challenges Challenges Pertaining to the Window Object Challenges Pertaining to the Document Object Challenges Related to the Globals Need for a Revolution Who Was the Revolutionary? Why jQuery? Minimal and Easy Coding Readable/Clean Code Easy CSS Handling Animation Methods Intuitive Function Calls Summary Chapter 2: Getting Started with jQuery Document Object Model (DOM) Downloading and Setting Up jQuery Downloading from the Official Web Site Including jQuery from a CDN CuuDuongThanCong.com https://fb.com/tailieudientucntt Clone from GitHub jQuery Fundamentals jQuery Syntax Document Ready Event jQuery noConflict() Method jQuery Selectors Working with jQuery The Problem Statement The Anonymous Function Preloading Images with jQuery each() in jQuery Summary Chapter 3: Traversing DOM with jQuery Selecting Elements with CSS Selectors Type Selector Universal Selector Attribute Selector Class Selector ID Selector Pseudo Class Selector Relationship-Based Selectors Using jQuery Selectors Type Selector Universal Selector Attribute Selector Class Selector ID Selector Pseudo Class Selector Other jQuery Selectors Traversing DOM with jQuery Traversal Methods The Curtain Raiser jQuery Methods for DOM Traversal Caching Selector and Chaining Methods Selector Caching Chaining CuuDuongThanCong.com https://fb.com/tailieudientucntt jQuery Filtering The eq() Method The filter() Method The first() Method The last() Method The has() Method The is() Method The not() Method Summary Chapter 4: DOM Manipulation with jQuery Editing Appearance with jQuery CSS Methods Obtaining CSS Properties Setting CSS Properties Setting Multiple CSS Properties Editing/Changing an Element’s Attributes, Contents, and Position Editing Attributes Editing Contents Creating and Inserting New DOM Elements append() vs .appendTo() Inserting New Elements in Specific Locations Putting the Methods to Work Removing and Cloning DOM Elements Working with Dimensions jQuery width() and height() Methods jQuery innerWidth() and innerHeight() Methods jQuery outerWidth() and outerHeight() Methods Summary Chapter 5: Events in jQuery Introducing Events Browsers and Events Event Listeners and Event Handlers The Event() Method in jQuery CuuDuongThanCong.com https://fb.com/tailieudientucntt Binding Events Unbinding Events Events Propagation and Events Bubbling The Event Capturing and Event Bubbling Models The W3C Event Model Callback Action in Event Summary Chapter 6: Real World Events in jQuery Common Gotchas in Event Handling Handling Dynamic Elements Handling jQuery Animation Buildup Preventing Event Propagation and Bubbling Handling the Event Queue How Handling Works in a jQuery Event Queue The jQuery queue() Method Building a jQuery UI Accordion Using the jQuery UI Accordion Customizing an Accordion Validating Form Elements Using the Validate Plug-in Validating Form Elements Using Customized jQuery Summary Chapter 7: Animation in jQuery Life Without jQuery jQuery’s animate() Fading in jQuery Using the fadeOut() Method Using the fadeIn() Method Using the fadeTo() Method Using the fadeToggle() Method Sliding in jQuery CuuDuongThanCong.com https://fb.com/tailieudientucntt break; } } Writing Another Test Case on the Refactored Code Now, if you want to write more test cases, since you have already separated the JavaScript code from the HTML page, you will just have to write more code inside the test runner file The code with another test case (the other test case was written by you to check the valid name functionality) would look like QUnit.test("Checking Valid Name", function(assert){ var validate = new Validation(); validate.name = 'Practical jQuery ED1'; assert.throws( function () { validate.check('name'); }, /Invalid characters in name/, "Input String Not Proper" ); }); QUnit.test("Checking Valid Phone", function(assert) { var validate = new Validation(); validate.phone = 'test123'; assert.throws( function(){ CuuDuongThanCong.com https://fb.com/tailieudientucntt validate.check('phone'); }, /Phone number needs to be worked upon/, "Input phone not proper" ); }); You have come a long way to be able to test the code that we wrote using jQuery We have always believed that more practice results in more expertise, and, therefore, we encourage you to find more such examples and try and write more and more test cases, so that you are able to write better quality code Summary With this, we come to the end of this chapter and the book In this chapter, you learned about the importance of testing to assure software quality You learned about unit testing and came to know what a unit is in relation to testing This chapter gave you information about QUnit, a framework written in JavaScript that is meant to automate the unit tests for the code written, not only in jQuery, but also in JavaScript in general While learning how to write test cases, you also learned how to refactor some code, to make it testable CuuDuongThanCong.com https://fb.com/tailieudientucntt Index A Accordion accordion() method creation customization slideUp() and slideDown() methods UI web site windows explore after() method Ajax definition functions HTML/CSS combination JavaScript JSON (see JavaScript Object Notation (JSON)) mother method—ajax() Netscape technologies web-based application angular.module() function Animations animate() method callback methods fast getCurrentPosition() method key:value format linear easing slow speed attribute swing engineering aspects fadeIn() method fadeOut() method fadeToggle() method fadeTo() method fx object getElement() method hide() method image slider checkAndSetLast() method code reviewers getDistance() method getElement() method CuuDuongThanCong.com https://fb.com/tailieudientucntt go() method HTML code jQuery code prepareRandomMovement() method replaceClass() method requirements interval property JavaScript code light box creation CSS code HTML code jQuery code setInterval method setTimeout method show() method slideDown() method slideToggle() method slideUp() method toggle() method callback action div element HTML code speed arguments swing/linear method turning off tweening algorithm Anonymous function JavaScript preloading images appendChild() function Attribute selector CSS selectors jQuery selectors attr() method B Beautification and uglification before() method C Caching selectors code cleansing HTML jQuery code meaning output results Callback method Chainability Chaining CuuDuongThanCong.com https://fb.com/tailieudientucntt children() method Class selector CSS selectors jQuery selectors clone() method closest() method Code clean Code cleansing Compression vs minification Content delivery network (CDN) Contents html() method position() method text() method CSS methods css() function multiple functions obtain properties setting properties tabular representation CSS selectors attribute selector class selector elements ID selector jQuery selectors pseudo class selector relationship-based selectors type selector universal selector Curtain raiser Customization D detach() method Dilemma—in Dimensions height() method innerWidth() and innerHeight() methods methods outerWidth() and outerHeight() methods width() method Distribution See Minification document.createElement() function Document object model (DOM) See also Traversal methods caching selector chaining CSS selectors jQuery Filtering (see Filtering) jQuery selectors CuuDuongThanCong.com https://fb.com/tailieudientucntt overview Document ready event DOM elements append() vs .appendTo() before() and after() creating and inserting elements HTML code insert elements removing and cloning DOM manipulation See also CSS methods contents dimensions editing attributes element (see DOM elements) E each() method empty() method eq() method eval() method Event() method building events currentTarget and relatedTarget event bubbling event.which property jQuery shorthand methods methods and properties mouseover and mouseout nodeName property types unbuilding events W3C model Event bubbling model Event capturing model Event handler Event listeners and event handlers change event click event createElement method keypress and keyup events mousemove method mouseover event removeEventListener() method window load event Event propagation and bubbling Events See also Real world events and user interactions browsers click event input element change event CuuDuongThanCong.com https://fb.com/tailieudientucntt keypress event mousemove event mouseout event mouseover event ready state window load event callback method capturing and bubbling DOM elements event handler event listeners and event handlers jQuery library prevent default propogation W3C event model web page interaction event.stopPropagation() method F fadeIn() method fadeTo() method fadeToggle() method filter() method Filtering eq() method first() method has() method is() method filter() method last() method methods not() method find() method first() method Form validation HTML data jQuery customization plug-in G get() method GitHub repository Google Code-hosting service Gotchas, event handling dynamic elements jQuery animation buildup library methods gt() selector CuuDuongThanCong.com https://fb.com/tailieudientucntt H has() method has() selector height() method hide() function html() method I ID selector CSS selectors jQuery selectors Image slider checkAndSetLast() method code reviewers getDistance() method getElement() method go() method HTML code jQuery code prepareRandomMovement() method replaceClass() method requirements innerWidth() and innerHeight() methods Integrating plug-ins See also Plug-in code clean dilemma—in elements external script tag find and download plug-in code script tag structure is() method J, K JavaScript AngularJS Bootstrap advantages buttons and icons, adding definition grid system navigation bar challenges document object global variables window object CuuDuongThanCong.com https://fb.com/tailieudientucntt document object document.createElement() method document.getElementById() method document.getElementsByClassName() method document.getElementsByName() method document.getElementsByTagName() method document.write() method tree representation history object back method forward method go method location object assign method hostname attribute href attribute pathname attribute reload method replace method navigator object overview screen object screen.availHeight property screen.availWidth property screen.height property screen.width property web browsers window object alert() method clearInterval() method clearTimeout() method focus() method innerHeight attributes innerWidth attribute outerHeight attributes outerWidth attribute setInterval() method setTimeout() method JavaScript See Anonymous function JavaScript Object Notation (JSON) criteria features parseJSON() method parsing preventDefault() method text-based data interchange use of jQuery animate method anonymous function CDN CuuDuongThanCong.com https://fb.com/tailieudientucntt color picker CSS handling Document Object Model document ready event each() method fundamentals GitHub internal queue handler intuitive function calls minimal and easy coding noConflict() Method official web site preloading images problem statement readable/clean code selectors slideToggle() method syntax UI accordion jQuery Mobile Ajax navigation system pop-up boxes RWD jQuery registry jQuery selectors attribute selector class selector CSS selectors ID selector pseudo classes type selector universal selector jQuery UI autocomplete datepicker draggable functionality drop function theming engine L last() method Library methods live() method LiveScript See Netscape load() method M Method chaining See Caching selectors Minification CuuDuongThanCong.com https://fb.com/tailieudientucntt beautification code creation vs compression difference uglified code mother method—ajax() Mozilla Development Network (MDN) N Netscape next() method noConflict() Method Node Package Manager (NPM) not() method O Official web site outerWidth() and outerHeight() methods P parent() method parents() method parentsUntil() method parse() method parseJSON() method Parsing JSON eval() method library methods options parse() method Plug-in accordion CSS code default values/passed parameters extend method HTML code in action business requirements, focus code modularity customization definition distribution ease of use form validation check method code implementation functionality CuuDuongThanCong.com https://fb.com/tailieudientucntt HTML form JavaScript method preventDefault method serialize method noConflict() method parameters private variables public variable repositories validation writing guidelines chainability jQuery object modify objects requirements reusability position() method post() method Preloading images preventDefault() method prev() method Propagation prop() method Pseudo class selector CSS selectors jQuery selectors Q queue() method QUnit assertion method check method deepEqual method DOM manipulation div element jQuery empty() method node, existing DOM test case, testing equal assertion method JavaScript framework method notEqual assertion method notOk assertion method overview refactoring code DOM manipulation test case Validation class returnValue method strictEqual assertion method CuuDuongThanCong.com https://fb.com/tailieudientucntt styling results syntax three arguments throws method unit testing carryOut methods check method check method do() method Validation class Validation class R Readability Real world events event propagation and bubbling gotchas jQuery UI accordion queue() method queues validating form elements Relationship-based selectors remove() methods Repositories GitHub Google Code-hosting service jQuery registry NPM open source package principle Responsive web design (RWD) S Script tag Selectors caching CSS elements elements fact files ID attributes jQuery query fast repeat event universal selector use of * wildcard siblings() method slideDown() method slideToggle() method slideUp() method CuuDuongThanCong.com https://fb.com/tailieudientucntt .stop() method T Tags text() method toggle() method callback action div element HTML code speed arguments swing /linear method Traversal methods children() method closest() method curtain raiser find() method next() method parent() method parents() method parentsUntil() method preceding code prev() method siblings() method structure and hierarchy tree traversal Tree traversal Type selector CSS selectors jQuery selectors U Uglification and beautification Unit testing carryout methods check method do() method Validation class Universal selector CSS selectors jQuery selectors V Validation plug-in W, X, Y, Z W3C event model CuuDuongThanCong.com https://fb.com/tailieudientucntt Web-based application width() method Window load event CuuDuongThanCong.com https://fb.com/tailieudientucntt ... are liable to prosecution under the respective Copyright Law ISBN-13 (pbk): 97 8-1 -4 84 2-0 78 8-8 ISBN-13 (electronic): 97 8-1 -4 84 2-0 78 7-1 Trademarked names, logos, and images may appear in this book... the three usages available: $('html-selector').css('css-property', 'css-value '); // Setting a single attribute $('html-selector').css({'css-property': 'css-value', }); //Setting multiple attributes... New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-8 00-SPRINGER, fax (201) 34 8-4 505, e-mail ordersny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California