Logout succeed
Logout succeed. See you again!

Beyond jQuery PDF
Preview Beyond jQuery
beyond jQuery — Ray Nicholus Beyond jQuery Ray Nicholus Beyond jQuery Ray Nicholus Johnson Creek Wisconsin, USA ISBN-13 (pbk): 978-1-4842-2234-8 ISBN-13 (electronic): 978-1-4842-2235-5 DOI 10.1007/978-1-4842-2235-5 Library of Congress Control Number: 2016953737 Copyright © 2016 by Ray Nicholus 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. 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 Acquisitions Editor: Louise Corrigan Development Editor: James Markham Editorial Board: Steve Anglin, Pramila Balan, Laura Berendson, Aaron Black, Louise Corrigan, Jonathan Gennick, Todd Green, Robert Hutchinson, Celestin Suresh John, Nikhil Karkal, James Markham, Susan McDermott, Matthew Moodie, Natalie Pao, Gwenan Spearing Coordinating Editor: Nancy Chen Copy Editor: Corbin Collins Compositor: SPi Global Indexer: SPi Global Cover Image: Courtesy of Freepik 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 [email protected] , or visit w ww.springer.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 [email protected] , or visit w ww.apress.com . Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at w ww.apress.com/bulk-sales . Any source code or other supplementary materials referenced by the author in this text are available to readers at w ww.apress.com . For detailed information about how to locate your book’s source code, go to w ww.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter. Printed on acid-free paper Contents at a Glance About the Author ...................................................................................................xiii Preface ....................................................................................................................xv Acknowledgments .................................................................................................xvii Introduction ............................................................................................................xix ■ Chapter 1: The Oppressive Magic of jQuery ..........................................................1 ■ Chapter 2: You Don’t Need jQuery (Anymore) ......................................................11 ■ Chapter 3: Understanding the Web API and “Vanilla” JavaScript .......................19 ■ Chapter 4: Finding HTML Elements ......................................................................31 ■ Chapter 5: Using and Understanding HTML Element Attributes ..........................53 ■ Chapter 6: HTML Element Data Storage and Retrieval ........................................69 ■ Chapter 7: Styling Elements ................................................................................81 ■ Chapter 8: DOM Manipulation ..............................................................................97 ■ Chapter 9: AJAX Requests: Dynamic Data and Page Updates ...........................109 ■ Chapter 10: Browser Events ..............................................................................133 ■ Chapter 11: Mastering Asynchronous Tasks .....................................................161 ■ Chapter 12: Common JavaScript Utility Functions ............................................179 ■ Chapter 13: Going Forward ................................................................................207 Index .....................................................................................................................213 iii Contents About the Author ...................................................................................................xiii Preface ....................................................................................................................xv Acknowledgments .................................................................................................xvii Introduction ............................................................................................................xix ■ Chapter 1: The Oppressive Magic of jQuery ..........................................................1 Why Have We Been Using jQuery? ...................................................................................2 Simplicity ................................................................................................................................................2 Community .............................................................................................................................................2 Habit .......................................................................................................................................................2 Elegance .................................................................................................................................................3 Fear ........................................................................................................................................................4 A Crutch Is Only Temporary ..............................................................................................4 You Are a Mechanic, Not a Driver............................................................................................................5 Stunted Growth .......................................................................................................................................6 The Price of Shortcuts (a True Story) ................................................................................7 A New Direction, a New Web Developer .................................................................................................7 Shortcuts and My Own Stunted Growth .................................................................................................7 A Challenge: No jQuery Allowed! ............................................................................................................8 Focus on the Implementation, Not the Magic ...................................................................9 v ■ CONTENTS ■ Chapter 2: You Don’t Need jQuery (Anymore) ......................................................11 Need vs. Want ................................................................................................................11 Both Sides of the Acceptable Use Argument ..................................................................12 When Is It Acceptable to Use It? ...........................................................................................................12 When Should You Refrain from Using It? ..............................................................................................13 Should You Use Other Libraries Instead? .......................................................................16 Small Shims Over Large Wrappers .......................................................................................................16 Writing Your Own Shim .........................................................................................................................17 The Final Word ................................................................................................................18 ■ Chapter 3: Understanding the Web API and “Vanilla” JavaScript .......................19 Everything You Need to Know About Browsers ..............................................................19 Ancient Browsers .................................................................................................................................20 Modern Browsers .................................................................................................................................21 Evergreen Browsers .............................................................................................................................21 Mobile Browsers ...................................................................................................................................22 Non-browsers .......................................................................................................................................23 What Is This Web API and Why Is It Important? ..............................................................23 The DOM API .........................................................................................................................................23 Everything Else (non-DOM) ...................................................................................................................26 JavaScript: A Less Elegant Version of jQuery? ...............................................................26 The Language vs. the Web API ..............................................................................................................27 History and Standardization .................................................................................................................28 ■ Chapter 4: Finding HTML Elements ......................................................................31 Core Element Selectors ..................................................................................................31 IDs.........................................................................................................................................................32 Classes .................................................................................................................................................33 Element Tags ........................................................................................................................................35 Pseudo-classes ....................................................................................................................................37 vi ■ CONTENTS Selecting Elements Based on Their Relations ................................................................38 Parents and Children ............................................................................................................................38 Siblings .................................................................................................................................................41 Ancestors and Descendants .................................................................................................................45 Mastering Advanced Element Selection .........................................................................48 Excluding Elements ..............................................................................................................................48 Multiple Selectors .................................................................................................................................50 Element Categories and Modifi ers ........................................................................................................50 A Simple Replacement for $(selector) ............................................................................52 ■ Chapter 5: Using and Understanding HTML Element Attributes ..........................53 What Is an Attribute? ......................................................................................................53 History and Standardization .................................................................................................................54 How Do Attributes Differ from Properties? ...........................................................................................55 Finding Elements Using Attributes .................................................................................57 Finding Elements Using Attribute Names .............................................................................................57 Finding Elements Using Attribute Names and Values ...........................................................................59 The Power of Wildcard and Fuzzy Attribute Selectors ..........................................................................60 Reading and Modifying Element Attributes ....................................................................62 Class Attributes.....................................................................................................................................63 Data Attributes ......................................................................................................................................66 Working with Other Standard and Custom Attributes ...........................................................................66 ■ Chapter 6: HTML Element Data Storage and Retrieval ........................................69 Why Would You Want to Attach Data to Elements? .........................................................69 Tracking State .......................................................................................................................................69 Connecting Elements ............................................................................................................................70 Storing Models Directly in Your Elements .............................................................................................70 Common Pitfalls of Pairing Data with Elements .............................................................71 Memory Leaks ......................................................................................................................................71 Managing Data .....................................................................................................................................72 vii ■ CONTENTS Using a Solution for All Browsers ...................................................................................72 Storing Small Bits of Data Using data- Attributes .................................................................................73 Complex Element Data Storage and Retrieval ......................................................................................75 The Future of Element Data ............................................................................................78 The HTML5 Dataset Property ................................................................................................................78 Leveraging ECMAScript 2015 WeakMap Collections ......................................................79 ■ Chapter 7: Styling Elements ................................................................................81 There Are Three Ways to Style Elements ........................................................................81 Inline Styles ..........................................................................................................................................81 Working with Styles Directly on the Element Object ............................................................................83 Style Sheets ..........................................................................................................................................85 Getting and Setting Generalized Styles ..........................................................................87 Using jQuery .........................................................................................................................................88 Without jQuery ......................................................................................................................................88 Setting and Determining Element Visibility ....................................................................89 The Typical jQuery Approach ................................................................................................................90 The Native Web Approach .....................................................................................................................90 Determining Width and Height of Any Element ..............................................................92 Examining an Element Using jQuery .....................................................................................................93 Options Natively Provided by the Browser............................................................................................94 ■ Chapter 8: DOM Manipulation ..............................................................................97 The DOM: A Central Component of Web Development ...................................................97 jQuery Exists Because of the DOM API .................................................................................................97 The DOM API Isn’t Broken, It’s Just Misunderstood ..............................................................................98 Moving and Copying Elements .......................................................................................98 Moving Elements Around the DOM .......................................................................................................98 Making Copies of Elements ................................................................................................................102 viii ■ CONTENTS Composing Your Own Elements ....................................................................................103 Creating and Deleting Elements .........................................................................................................103 Text Content ........................................................................................................................................105 Rich Content .......................................................................................................................................107 ■ Chapter 9: AJAX Requests: Dynamic Data and Page Updates ...........................109 Mastering the Concepts of AJAX Communication ........................................................109 Async Is Hard ......................................................................................................................................110 HTTP ...................................................................................................................................................110 Expected and Unexpected Responses ................................................................................................111 Web Sockets .......................................................................................................................................111 Sending GET, POST, DELETE, PUT, and PATCH Requests ...............................................111 Sending POST Requests .....................................................................................................................113 Sending PUT Requests .......................................................................................................................114 Sending DELETE Requests ..................................................................................................................115 Sending PATCH Requests ...................................................................................................................115 Encoding Requests and Reading Encoded Responses .................................................116 URL Encoding .....................................................................................................................................116 JSON Encoding ...................................................................................................................................119 Multipart Encoding .............................................................................................................................122 Uploading and Manipulating Files ................................................................................124 Uploading Files in Ancient Browsers ..................................................................................................124 Uploading Files in Modern Browsers ..................................................................................................126 Reading and Creating Files .................................................................................................................127 Cross-domain Communication: an Important Topic .....................................................128 The Early Days (JSONP) ......................................................................................................................128 Modern Times (CORS) .........................................................................................................................129 ■ Chapter 10: Browser Events ..............................................................................133 How Do Events Work? ..................................................................................................133 Event Types: Custom and Native .........................................................................................................134 Event Propagation: Bubbling vs. Capturing ........................................................................................134 ix ■ CONTENTS Creating and Firing DOM Events...................................................................................136 Firing DOM Events with jQuery ...........................................................................................................137 Web API DOM Events ..........................................................................................................................138 Creating and Firing Custom Events ..............................................................................139 jQuery Custom Events ........................................................................................................................139 Firing Custom Events with the Web API ..............................................................................................140 Listening (and Un-listening) to Event Notifi cations ......................................................141 jQuery Event Handlers ........................................................................................................................141 Observing Events with the Web API ....................................................................................................142 Controlling Event Propagation ......................................................................................144 Passing Data to Event Handlers ...................................................................................146 Event Delegation: Powerful and Underused .................................................................147 Handling and Triggering Keyboard Events ....................................................................150 Three Types of Keyboard Events .........................................................................................................150 Identifying Pressed Keys ....................................................................................................................151 Making an Image Carousel Keyboard Accessible with the Web API ...................................................152 Determining When Something Has Loaded ..................................................................153 When Have All Elements on the Page Fully Loaded and Rendered with Applied Styles? ...................154 When Has All Static Markup Been Placed on the Page? .....................................................................155 When Has a Particular Element on the Page Fully Loaded? When Has It Failed to Load? ..................155 Preventing a User from Accidentally Leaving the Current Page .........................................................156 A History Lesson: Ancient Browser Support .................................................................157 The API for Listening to Events Is Non-standard ................................................................................157 Form Field Change Events Are a Minefi eld .........................................................................................158 The Event Object Is Also Non-standard ..............................................................................................159 x