Learning JavaScript: A Hands-On Guide To The Fundamentals .

3y ago
65 Views
12 Downloads
618.69 KB
63 Pages
Last View : 13d ago
Last Download : 1m ago
Upload by : Farrah Jaffe
Transcription

Praise for Learning JavaScript“Between modern web interfaces, server side technologies, and HTML5 games,JavaScript has never been a more important or versatile tool. To anyone just startingout with JavaScript or looking to deepen their knowledge of the practical core of thelanguage, I would highly recommend Learning JavaScript.”—Evan Burchard, Independent Web Developer“Although I’ve read a couple of books about JavaScript before, as a backend developer,I was thrilled to see Tim Wright’s Learning JavaScript. The nuances of progressiveenhancement versus graceful degradation are finally explained in a manner thatsomeone new to front-end coding can understand. Bravo, Tim.”—Joe Devon, Cofounder, StartupDevs.com“Tim Wright has written a delightfully practical book for the novice front-enddeveloper who wants to learn JavaScript. This book’s strength is in providing a goodintroduction to JavaScript while also illustrating the context of when and where itshould be used.”—R. S. Doiel, Senior Software Engineer, USC Web Services“Learning JavaScript is a great introduction into modern JavaScript development. Fromcovering the history to its exciting future, Learning JavaScript equips the novice developerto practical application in the workforce. I wish this book came along when I was a novice!”—Hillisha Haygood, Senior Web Developer, Sporting News“Tim presents invaluable techniques for writing JavaScript with progressiveenhancement at the forefront. If you are new to JavaScript then this book will proveto be a great asset in your learning. Covering all the basics and then right through totouch events, AJAX, and HTML5 APIs, the examples are clear and easy to follow. Usingthis book, you will learn when and how to use JavaScript to great effect.”—Tom Leadbetter, Freelance Web Designer“Learning JavaScript is valuable for both new and veteran developers. It is great for newdevelopers because it is easy to read and provides a step-by-step process to becominggreat at JavaScript. Veteran developers will be reminded of many of the best practicesthey have already forgotten.”—Christopher Swenor, Manager of Technology, zMags

Addison-Wesley Learning SeriesVisit informit.com/learningseries for a complete list of available publications.The Addison-Wesley Learning Series is a collection of hands-on programmingguides that help you quickly learn a new technology or language so you canapply what you’ve learned right away.Each title comes with sample code for the application or applications built inthe text. This code is fully annotated and can be reused in your own projectswith no strings attached. Many chapters end with a series of exercises toencourage you to reexamine what you have just learned, and to tweak oradjust the code as a way of learning.Titles in this series take a simple approach: they get you going right away andleave you with the ability to walk off and build your own application and applythe language or technology to whatever you are working on.

LearningJavaScript

This page intentionally left blank

LearningJavaScriptA Hands-On Guideto the Fundamentalsof Modern JavaScriptTim WrightUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCape Town 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 initial capitalletters or in all capitals.Editor-in-ChiefMark TaubThe author 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 connection with orarising out of the use of the information or programs contained herein.DevelopmentEditorSonglin QiuThe 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 covers andcontent particular to your business, training goals, marketing focus, and branding interests.For more information, please contact:U.S. Corporate and Government Sales(800) 382-3419corpsales@pearsontechgroup.comFor sales outside the United States, please contact:International Salesinternational@pearson.comVisit us on the Web: informit.com/awLibrary of Congress Cataloging-in-Publication dataWright, Tim, 1982Learning JavaScript : a hands-on guide to the fundamentals of modern JavaScript /Tim Wright.pages cmIncludes bibliographical references and index.ISBN 978-0-321-83274-0 (pbk. : alk. paper) -- ISBN 0-321-83274-4 (pbk. : alk. paper)1. JavaScript (Computer program language)--Handbooks, manuals, etc. I. Title.QA76.73.J38W755 2013005.2’762--dc232012019351Copyright 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 use material from this work, please submit a written request to Pearson Education, Inc., PermissionsDepartment, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax yourrequest to (201) 236-3290.ISBN-13: 978-0-321-83274-0ISBN-10: 0-321-83274-4Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor,Michigan.First printing, August 2012Acquisitions EditorLaura LewinManaging EditorKristy HartProject EditorAnne GoebelCopy EditorBarbara HachaIndexerLisa StumpfProofreaderDebbie WilliamsTechnicalReviewersEvan BurchardAlex MoffatPublishingCoordinatorOlivia BasegioCover DesignerChuti PrasertsithCompositorNonie Ratcliff

For Ma.

ContentsIntroduction1Chapter 1:Progressive Enhancement3Chapter 2:JavaScript in the Browser21Chapter 3:JavaScript TerminologyChapter 4:Accessing the DOMChapter 5:Storing Data in JavaScriptChapter 6:Variables, Functions, and Loops 103Chapter 7:Interacting with the User Through EventsChapter 8:Communicating with the Server Through Ajax 149Chapter 9:Code OrganizationChapter 10:Making JavaScript Easier with Libraries 211Chapter 11:HTML5 JavaScript APIsChapter 12:Moving Forward with JavaScript 273Answers 305Index 309395781123179243

ixTable of ContentsIntroduction 1Chapter 1:Progressive Enhancement 3Defining Progressive Enhancement 3History 4Purpose5Accessibility 5Reusability 5Progressive Enhancement Versus GracefulDegradation 6Structure Layer 6Adding More Meaning with HTML5 8Presentation Layer 9Inline CSS 10Linking Up Your Stylesheet 10Behavior Layer 12Inline JavaScript 12Embedded JavaScript 13External and Unobtrusive JavaScript 15Benefits of Progressive Enhancement 16Performance 17Building for the Future 17The Touch Interface 18Final Words on Progressive Enhancement 19Summary20Exercises 20Chapter 2:JavaScript in the Browser 21A People’s History of JavaScript21Origins 22Progressive Enhancement 23The Behavior Layer 24Moving Past Today 24Browser Interactions with JavaScript 25HTTP Requests26JavaScript and Rendering Engines 29

xContentsWhat JavaScript Can Do 30Modifying HTML 31Communicating with the Server 31Storing Data 31How You Should Use JavaScript 32Improving User Experience 32Using JavaScript Responsibly 32Creating Fallbacks 34Tools to Help You Use JavaScript 36Tools Built into the Language 36Tools Built into the Browser 37Summary38Exercises 38Chapter 3:BasicsJavaScript Terminology 3939Document Object Model (DOM) 39Parents40Children 40Siblings 41Variables 41Strings43Comments 43Operators 44Use t Object Notation (JSON) 46Objects 47Creating Interaction 47Loops48Conditionals 48switch Statement 49Functions 50Anonymous Functions 51

ContentsCallback Functions 52MethodsEventsAjax535454Summary55Exercises 55Chapter 4:Accessing the DOM 57What Is the DOM? 57The DOM Tree 58Element Nodes 59Text Nodes 60Attribute Nodes 62Working with the Element Node 62Targeting by ID 63Targeting by Tag Name 64Targeting by Class 67Using CSS Selectors in JavaScript to Target Nodes 68Working with the Attribute Node 70Getting an Attribute 71Setting an Attribute 72Removing an Attribute 73Working with the Text Node and Changing Content 73Moving Around the DOM 74Accessing First and Last Child 76Dynamically Adding and Removing Nodes from theDOM 77Adding Elements to the DOM 77Removing Elements from the DOM 78Summary79Exercises 79Chapter 5:Storing Data in JavaScript 81Variables 81Strings82Numbers 83Boolean84Performance in Variables 84xi

xiiContentsArrays85Basic Array85Associative Array 87Multidimensional Array 87Pushing Data into an Array 89Working with Array Methods 89join90slice90shift and unshift 91pop92concatsort9293Objects 93Performance in Objects 94JSON95Benefits of Using JSON 96Using an API 96Web Storage in HTML5 97localStorage and sessionStorage 97setItem97getItem98removeItem 98Storing Chunks of Data with JSON 99Using Web Storage Responsibly 100Summary101Exercises 101Chapter 6:Variables, Functions, and Loops 103Defining Variables 103Grouping Variables 104Reserved Terms 104Functions 105Basic Functions106Anonymous Functions 107Scope108Calling a Function with a Function 109Returning Data 110A Function as a Method 112

ContentsLoops113for Loop114Conditionals 116if Statement116if/else Statement117switch Statement118if versus switch119Putting It All TogetherSummary120121Exercises 122Chapter 7:Interacting with the User Through Events 123Attaching an Event 124Event Handlers 124Event Listeners 125Binding Events 128Unbinding Events 129Mouse and Keyboard Events 130click132focus and blur 134Accessibility 135change135mouseover and mouseout (hovering) 136submit137Preventing Default Behavior 139keydown, keypress, and keyup 139Putting It All Together 140Touch and Orientation Events 143touchstart and touchend 144touchmove 145orientationchange 145Support for Touch Events 146Putting It All Together 147Summary148Exercises 148xiii

xivContentsChapter 8:Communicating with the Server ThroughAjax 149Ajax History150Server CommunicationThe XMLHttpRequestCreating an Ajax Call151152154Sending a Request to the Server155Receiving Data Back from the ServerMaking Repeat Ajax Calls 163Ajax Data FormatsXML164165HTML166JSON167Ajax Accessibility168Live Regions and ARIACommon Ajax Mistakes169170Providing Feedback 170Putting It All Together 172Where Is Ajax Going? 177Summary177Exercises 178Chapter 9:Code Organization 179General Coding Style Rules 180Scope181Failing Quickly 183User Experience 185Code Design 185Files and Directories 186In-document Script 187Variable Declarations 188Variable and Function Naming 189Comments 190Indentation 192Whitespace 193Statement Spacing 194158

ContentsLine Breaks195Math and OperatorsUsing eval()196197Taking Style Guides Too FarCode Structure199200Functions 200Anonymous Functions 201Functions as Variables 202Functions as Methods 202JavaScript Development Patterns 204Summary208Exercises 209Chapter 10:Making JavaScript Easier with Libraries 211JavaScript Library Basics 212The Library Learning Process 213Syntax214Focusing on the Goal 214Creating Shortcuts 215Fixing Browser Issues 216Popular Libraries 216jQuery Basics 221document.ready 222Selectors 223Traveling Through the DOM 225Adding Style Information 226Binding Events 227Animation 227jQuery Nonbasics 228Using Ajax in jQuery 228Looping Through Data in jQuery 230Chaining Functions 232Extending Libraries Through Plug-ins 233Building a Plug-in 234The Good of Libraries 236Popularity and Community 236Efficient Code 237xv

xviContentsThe Bad of Libraries 238Overhead 238Performance 239Overreliance and Shelf Life 239Using Microlibraries 240The Good 240The Bad 241Summary242Exercises 242Chapter 11:HTML5 JavaScript APIs 243What Is HTML5? 244The Markup (aka HTML) 244Creating Better Semantics 245Building More Accessible Content 245The JavaScript APIs 248The navigator Object 248Geolocation 249Audio and Video 251History API 254Web Workers 259Device API 265The Battery Status API 266The Vibration API 267The Network Information API 268Using This Today with Feature Detection 270Summary271Exercises 272Chapter 12:Moving Forward with JavaScript 273A Brief Review of Key Topics274Progressive Enhancement 274DOM ManipulationData Storage275277Server Communication279

ContentsJavaScript for Designers 279Advanced Interface Design 280CSS Transforms in JavaScript 284Interacting from the Desktop 289JavaScript for Developers 293JavaScript Templates 294JavaScript on the Server with NodeJS 299Summary302Exercises 303Answers 305Index309xvii

This page intentionally left blank

AcknowledgmentsThere are a lot of people who contributed in some way to the completion of this book. Firstof all, I want to thank the folks at Pearson for giving me the opportunity to not only writethis book, but structure it in a way that truly reflects how I believe the topic should be taught.The book would not have stayed on track without them. My technical editors were alsoinstrumental to the process in pointing out any missteps, giving praise when needed, andmaking sure every detail of the book was written with accuracy and precision; I could not havedone it without you (Evan Burchard and Alex Moffat). I would also like to give special thanksto my parents, friends, and family for the continued support, encouragement, and patiencethroughout this long process and for pulling me out of my “writing cave” for fresh air everyonce in a while. Without you all, nothing would have been possible.

About the AuthorTim Wright has been a Web designer and front-end developer since 2004, primarily focusingon CSS, HTML5, accessibility, user experience, and building applications with the capabilityto scale seamlessly from desktop to mobile device. He has worked at various universitiesnationwide and fostered the advancement of Web standards at each stop along the way.Tim has written many articles for popular Web design online publications, such as SmashingMagazine, SitePoint, and Web Designer Depot, on all facets of front-end development fromHTML5 and CSS3 to user experience and advanced JavaScript techniques. He also writes manyarticles via his personal blog at csskarma.com. Tim holds a Bachelor’s Degree in MarketingManagement from Virginia Tech, with a specialization in Graphic Design.

IntroductionWhen I decided to write a book about JavaScript, I wanted to create it in a way that feltnatural to how I learned the language. I didn’t learn it from school or a book; my JavaScriptknowledge comes from real-world application, trial and error, and self-motivation. I wantedto present the information in a unique way so that you could get up to speed quickly, but stilldevelop a solid base for the language and move forward without feeling overwhelmed withtoo much information. I combined my teaching experience with how I felt while I was learning to create an environment that moves quickly but has built-in break points and reviews toalways keep the mind focused and clear. The JavaScript language can be confusing if taken allat once. There are hundreds of way to accomplish the same task, most of which you don’t needto know. I did my best throughout this book to not show too many ways to do the same thing,but rather focus on doing one thing really well.The organization of this book is a little different from that of a normal JavaScript book. Oftenterms are introduced, explained in real-time, and readers can feel like they are taking in toomuch information at once. This can cause a loss of focus on the main task at hand. I addressedthis issue by putting all the common JavaScript terms right up front in the book instead ofpiling them in a glossary that no one will read. As you go through them, they provide briefexplanations of many core concepts in the language. This way we don’t have to spend valuabletime giving broad definitions of miscellaneous terms and can focus on getting you the mostknowledge out of this short time we have together.The process of learning a robust language like JavaScript may seem intimidating at first, butdon’t worry, it’s not that bad. After you grasp some of the basic ideas, the rest is like learning aspoken language; the hard part is properly organizing it, performance tuning, and most of all,knowing when to use CSS instead. Hopefully, by the time you’re finished reading this book,you will have gained the knowledge you need to effectively create a better user experience byresponsibly using JavaScript.JavaScript is a language with an amazingly rich history and an even brighter future.Throughout this book you learn the basics of the language, but at the same time you learnmore advanced topics, such as HTML5 JavaScript APIs and how you create a touch-enabledinterface. You can be assured that even though JavaScript is code, it’s far from boring; you cancreate some pretty wild interfaces and have a lot of fun in the process.I hope this book can serve you well for years to come and will act as a launching pad for yourcontinued interest in JavaScript. If this is the first step in your journey to learning JavaScript,welcome aboard; if you already know the language, welcome back.

2IntroductionTarget Audience for This BookThe audience for this book is anyone starting out in Web design and development who wantsto learn about JavaScript. Before reading this book, you should be knowledgeable in HTML andCSS, and be familiar with the concepts behind progressive enhancement.This book can equally serve absolute beginners and seasoned Web veterans who are expandingtheir knowledge into JavaScript. All the while, I hope it instills enthusiasm to learn more aboutthis rapidly moving industry.Code Samples for This BookThe code samples for this book are available on the book’s website athttp://learningjsbook.com.

6Variables, Functions,and LoopsThis is one of the more important chapters in the book because you learn some of thecore features in JavaScript. We expand on the variables that were mentioned in the previouschapter, then move on to creating functions, and last, we go over how to loop through data toautoexecute the same code block over and over. Using variables, functions, and loops are oftenthe only thing a person knows how to do in JavaScript, and they usually get along just fine.You’re already past that part and on your way to becoming an elite JavaScript developer, so noworries there. You’ll be coding while all the others are looking up how to do something.Now that you have a solid base in how to work with a lot of the common things in JavaScript,you can start building an application and producing something tangible. Up to this point inthe book, the examples have been pretty specific, but also a little abstract. You’ve been manipulating content and data, then alerting or observing the result. In this chapter we expand onwhat you’ve learned already and begin building a simple JavaScript application that will getmore robust as you step through the subsequent chapters.As you progress though this chapter, you notice that an address book application should bestarting to form. Some of the methods that we go over repeat in their core functionality buthave very different use-cases. Although they may not necessarily all live in the same application, this is the chapter where you start building that tangible knowledge that can be directlytransferred into a project.Defining VariablesFor the most part, you learned about variables within the context of data storage, but they alsohave an integral part in your application when it comes to functionality.When considering variable and function naming, it’s best to make them meaningful and speakto their contents or purpose

introduction to JavaScript while also illustrating the context of when and where it should be used.” —R. S. Doiel, Senior Software Engineer, USC Web Services “Learni ng JavaScript is a great introduction into modern JavaScript development. From covering the history to its exciting future, Learning JavaScript equips the novice developer

Related Documents:

JavaScript Manual for LCCS Teachers 13 Client-side JavaScript vs. server-side JavaScript For many years JavaScript was a client-side scripting language. This was because JavaScript programs could only be run from inside web browsers which were installed on client machines. Because of the fact that JavaScript code can run on client devices it means

- The Spark web app framework . Yahoo JavaScript PHP Amazon.com JavaScript Java, C , Perl Wikipedia.org JavaScript PHP, Hack Twitter.com JavaScript C , Java, Scala, Ruby Bing JavaScript ASP.net eBay.com JavaScript Java, JavaScript, Scala . Note the MVC architecture

JavaScript directly within the HTML file. We can also include more than one script tag and can include a mix of internal JavaScript and external JavaScript files. This will be useful, for example, if we have some JavaScript that is appropriate for many of our webpages and then some JavaScript that is specific to one page. Function Definition

JavaScript. Check a framework's documentation for details. Using the SDK with Web Browsers All major web browsers support execution of JavaScript. JavaScript code that is running in a web browser is often called client-side JavaScript. Using the SDK for JavaScript in a web browser differs from the way in which you use it for Node.js. The

Praise for Effective JavaScript "Living up to the expectation of an Effective Software Development Series pro-gramming book, Effective JavaScript by Dave Herman is a must-read for anyone who wants to do serious JavaScript programming. The book provides detailed explanations of the inner workings of JavaScript, which helps readers take better

JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages This tutorial is about JavaScript, and how JavaScript works with HTML and CSS. Learning Speed In this tutorial, the learning speed is your choice.

JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:

blue K1. R(s,2) s is also a simple result; if all the edges of Ks are coloured red, it will contain a red Ks, however if one edge is coloured blue it will contain a blue K2. The edges of any graph of order less that s could all be coloured red in which case the graph would contain neither a red Ksor a blue K2.