100% found this document useful (5 votes)
1K views

JavaScript-JQuery-Jon-Duckett New

JavaScript-JQuery-Jon-Duckett new

Uploaded by

IliasAhmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (5 votes)
1K views

JavaScript-JQuery-Jon-Duckett New

JavaScript-JQuery-Jon-Duckett new

Uploaded by

IliasAhmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 650
JAVASCRIPT SO & JQUERY ett Reel te} Poems culs JON DUCKETT JAVASCRIPT & JQUERY Interactive Front-End Web Development JON DUCKETT Additional materia by GILLES RUPERT & JACK MOORE WILEY Mt Published by Joba Wiley & Sons ne 10475 Crosspoint Boulevard Indianapolis, IN 46256 soon Tey.com ©2014 by John Wiley & Sons, ne, Indianapolis, Indiana (aN; 978-1-118-59166-8 ‘Manufactured inthe United States of America 10987654321 Nopatltnis picaton may be repre, sored na eta tn rwanda ny fr ary means leon, mecank Pototoyie cang xanga" thera, ecet eprint Secon 107 oI! he 176Ustus Stes Copy et ‘thou ee per wl person Puhr rasan vou ayes lth porn pero t o Copy Clearance Cert 22 ovens Dive, Durer MA }23 (978) 50-840 (378 66-8600 Raquela uber peso shale aaiesed te Permisions Dupre ln Wey & Ser. ee Roe Set Hebien,W) O73, (20 7a {607 fae 200 78-4008 or ones Htp// wane. cm/o/oemio Unit Ubity/Diclaer of Waray: Te abs pdb our make rorereseraens warns wh respel tote acre ‘rronpistrest ol comers ewok andspeccly cco s.r alr hat mean waar reset Spree pron Howrarymoy be etd aetna bys pramnosimatass Tha yoece ond seis conned arena ate utaelorevery tuations wok aso tthe uncrstndeg tthe pba iat engaged enn eh scouting. cher rlsiona serves. paeseal asstance rege heserdcesol compete prlesson prion sos ‘aout Nate the pbloer othe autor alt blo drapes aig heron TR lc ht ncrgoianor Web tes ‘eredo ins wre oe atatn a/b 3 oer sauce helms dest mean tha he uo ube enor \westes ian ths worky hve hanged Gsopenred betwee whens wok ws Won and Wien i538. gens rman enous products nd erics lace cntet ow Customer Cav Deparimenwihinthe Unt Sts (877) “7629976 co tha Unto Siar (317) S72 993 0c 572-4002 Wiley aes avait of pita elev ort aby pica dean Some materi ced wih standard pint esr ‘paboak oy otbecucedine oats rn pron deroné thi book lerto med suenas scD 0" OVD atishl add nthe ‘rtonyoupucaed, you ny mrad ha matra t Mo//Soksupporeycom. Fr mere nomaon tot Wey products is setey com Ua ConrssComrelNumber 2018985952 “ademas: Wer ane Wey log se adem cretred ademars foe Wy & Sons, Ine and/or fies, ne Ud Sse ante cures ray bese et writen gemson Jers sere ode of Oral ei: thr vasenae the prperty hor pete oer hn Win Sens ea esate way precutr ent mentioned TABLE OF CONTENTS eer tay Ce Ceri ree ea ar Chapter 3: Functions, Methods & Objects Chapter 4: Decisions & Loops ore ae ese oe ae Tcl eat ag eee ae et ere] eae Cea a eee Cee Oa Chapter 12: Filtering, Searching & Sorting er aE ee id oly DOWNLOAD Biome as Reel Rul cere ARIE eg N i www. javascriptbook.com CREDITS For John Wiley & Sons, ne For Wagon Ltd. Executive Ealtor Author Carol Long Jon Duckett Project Editor co-Authors Kevin Kent Jack Moore ‘Chapters 1.612) Production Editor Daniel Scribner Giles Ruppert (Chapter 13) Editorial Manager Mary Beth Wakefield Technical Review ‘Mathias Bynens Associate Director of Marketing David Mayhew Review Team Chris Ullman ‘Marketing Manager David Lean Lorna Min Harison Tht Jay Bursky Business Manager Richard Eskins “Amy Koies Scott Robin Stachu Korck Vice President and Executive Group Publisher Thank you Richard Swadiey ‘Annette Loudon ‘Michael Tomko Associate Publisher ‘Michael Vella Zarb Jin Minate Pam Coca Rishabh Pugalia Project Coordinator, Cover Toca klemme ‘cover Desien Fmme Stone Design Emme Stone Jon Duckett Photography Joh Stewardson Jobnstevardson.con IMstration Matthew Cancich (Hotel in Chapter3) Emme tone (Teacher in Chapter 4) ‘Additional Photography Electronics in Chapters 8 & 9: ‘Aaron Nielsen Arkadiusz Jan Sikorski Matt ers Mirsad Dedovie Steve Lodetink Javascriptbook.con/eredits INTRODUCTION This book explains how JavaScript can be used in browsers to make websites more interactive, interesting, and user-friendly. You will also learn about iQuery because it makes writing JavaScript a lot easier. To get te most out ofthis book, you wl need to know howto bul webpages Using HTML ‘and CSS, Beyond that, o prior experience with programming is necessary, Learning to rogram with lavaScript involves 1 2 3 Understanding some basie Learning the language tse, Gecoring familia with how programming concepts and and ike allanguages, you itis applied by looking at theterms that JavaScript need toknowits vocabulary examples of how lovaSeriot programmers useto andhow tostructure your iscommonly usedin describe them, sentences, websites today ‘The only equipment you need touse this book re a computer with s modern wab browser Install, and your favorite code editor, (eg. Notepad, TextEdit, Sublime Testor Cod). @ wren Introduction pages come atthe beginning of each chapter. They inlroduce the key topes ou wil lara out Background pages appear on white. They explain the contest ofthe topics covered that are discussed Ingach chapter. Fa Example pases bring together the topics youhave learned in that chapter and demonstrate how they canbe applies Reference pages introduce key peces of JavaScript HTML code is shown in bi, CSS code in pink and JavaScript in green Diagram and infographics pages are shown on 8 dark background. They provide a simple, vis reference to opis discussed. Summary pages com atthe end ol each chapter They remind youcf thekey topics that were covered Ineach chapter. Pa ea PC aes eoauc ee eee) modifying the content and Doge eae Rete while it is being viewed in ee 1 ESS CONTENT we tert inside al ofthe 2 MODIFY CONTENT You conse jmaScript to xt tothe elements, ati class new CSS rules ceeaiag Oey CCCI tag ec Ree CUR acl REACT TO EVENTS interactive by responding y OU UL es oe EXAMPLES OF JAVASCRIPT IN THE BROWSER Being able to change the content of an HTML page while it is loaded in the browser is very powerful. The examples below rely on the ability to: ‘Access the content of the page ‘Modify the content of the page Program rules or instructions the browser can follow React to events triggered by the user or browser SLIDESHOWS Shown in Chapter) Slideshows can display 8 number of diferent images (orother HTMIL content) within the same space ‘ona given page. They can ploy automatialy as ‘sequence, or users can click through the sides ‘manualy They allow more content tobe displayed \ithina limited amount of space, React: Script triggered when the page loads ‘Access: Get each side rom the slideshow ‘Modify: Only show the fist slide chide others) Program: Seta timer: when to show next slide ‘Modify: Change which sides shown React: When user clicks button for cilerent slide rogram: Determine which side to show ‘Modify: Show the requested side © mrnooverion FORMS Shown in Chapter 13 Validating forms checking whether they have been filled in corect) important when information is supplied by users. avaSerpt ets you alert the user if mistakes have been made lt can also perform sophisticated calculations based on any data entered ‘and reveal the results tothe use React: User presses the submit button when they have entered teirname ‘Access: Get value from form Held Program: Check thatthe name long enaugh Medify: Show s warsing message ifthe name is not long enough ‘The examples on these two pages sive youa taste of what JavaScript can dowithin a web page, and ofthe techniques you willbe learning throughout this book. RELOAD PART OF PAGE Showin Chapter 8 ‘You might nat want to force vistors to reload the content ofan entire web page, particularly if you only need to refresh a ema portion of page Just reloading a section ofthe page can make a site fe! ike tis aster to load and more ike an application React: Script triggered when user clicks on nk ‘Access: Thelin tot they clicked on Program: Load the new content that was requestes from that ink ‘Access Find the elament toreplce inthe page ‘Modify: Replace tat content with the new content Inthe coming chapters. you wil learn how and when to accessor modily content, ad programming rues, and react to events ce 7a i. ia SE at & FILTERING DATA Shown in Chapter 12 HH youhave 2 lt of information to display on 3 page, you an help uses find information they need by Providing fiers. Here buttons are generated using fata inthe attributes ofthe HTML elements. ‘When the user clicks on one ofthe butions, they are only shown the images with that keyword. React: Serio triggered when page loads Program: Collect keywords trom images Program: Turn the keywords into buttons the user canclickon React: User clicks on one ofthe buttons Program: Fins the relevant subset of imoges that should be shown ‘Modify: Show the subse of images that use that tg wermosuenon (7) THE STRUCTURE OF THIS BOOK In order to teach you JavaScript, this book is divided into two sections: CORE CONCEPTS “Theft nine chapters introduce you tothe bases ‘of programming and the JavaScrit language. Along ‘the way youwil learn how itis used to create more ‘engaging. interactive, and usable websites. Chapter tlooks at some key concepts in computer programming showing you how computers create models of the word using daa, and how JavaScript isused to change the contents ofan HTML page ‘Chapters 2-4 cover the basis ofthe JavaScrot lanavoee. ‘Chapter 5 explains how the Document Object Model (DON) ets you access and change a document's contents while it is loaded into the browser. (Chapter 6 discusses how events canbe used to trigger code. {Chapter 7 shows you how {Query can make the process of wing script faster and easier ‘Chapter introduces youto Ajax ast of techniques that allow you to ust change part of ‘web page without eloacing the entire page. Chapter 9 covers Applicaton Programming Interfaces (APIs, including new APIs that are port of IMLS and thoseof sites ike Google Maps. @ wroouerion PRACTICAL APPLICATIONS By this point you wil already have seen meny ‘examples of how JavaScrintis used on popular ‘websites This section brings together al ofthe techniques you hae earned so fa, to give you practical demonstrations af how lavaScrptis used by professional developers. Not ony wil you see & selection of in-depth examples you wills learn more about the process of dsigrng and writing scripts from scratch ‘Chapter 10 deale with errorhanding ond debuasing, and explains more about how JavaScript is processed. ‘Chapter Tt shows you techniques for creating content panels such as siers, moda windows, tabbed panes, and accordions. Chapter 12 demonstrates severl techniques for fering an sorting dato, This includes filtering 3 szaliery of images, and re-ordering the rows ofa table by cieking onthe column headings ‘Chapter 13 deals with form enhancements and how toaldate form entries Uniess you ae already a confident programmer. you vill probably init helpful to read the book from start ois the fst ime, However, once youhave srasped the basis, we hopeit ill continue to bea helptl elerence as you create your own sits HTML & CSS: A QUICK REFRESHER Cee ae er ee a ee Dee RU ce ROE cela RCAC oe pee td Dees ee ee ee ced ee ee ec aera ert eee ee eee en ee pee eee ceemaneaeres) ceo eaten Pree peice et ae ee ce

peach

n ee See ee em cee ee ere as ieee which elements) the Peete eee apples o, The declaration block (the aspect you want to contro, rien ee eee re cr ee RC selector andadeciaratonblock. those elements shouldappear. _forthat propery. aaa ahem clr Leet fa Sy rar tne) BROWSER SUPPORT Some early examples i this book do not work with Internet Explorer 8 and earlier (but alternative code samples that work in IE8 are available to download from http: //javascriptbook. com). We explain techniques for dealing with older browsers in later chapters. Each version ofa web browser adds new features, Often these new features make tasks easier, or are considered beter, than using older techniques But, wobsite vistors do not always keep up with the atest browser releases, so website developers cannot aay ely upon the latest technologies. ‘As you wll see, there are many inconsistencies between browsers that affect JavaScript develoners Query wll help you deal with cross-browser Inconsistencies (its one ofthe major easons why Query rapidly gained popularity amongst wed = == =) =. You need to learn to “think” like a computer because they solve tasks in different ways than you or I might approach them, Computers solve problems programmatically, they follow series of instructions, one after another. The typeof instructions they need are often cifferent to the typeof instructions you might give to another human. Therefore, thoughout th book you wil not ‘only learn the vocabulary and syntax that lavaScript uses, but you will also learn howto wt nstuctions that computers can follow. For example, when you lok tthe picture on the left how de you tll wich person s the tallest? ‘Acomputer would need expt, step-by-step Instructions, such as: 1. Find the height ofthe fst person 2.Assumehe or she the “tallest person” 3 Look atthe height ofthe remaiing people one- by-one and compare their height tothe tallest person" you have found so far 4,At each step, you find someone whose heights ‘reater than the curent “tallest person’ he or she ‘becomes the new tallest person 5.Once you have checked alhe people tel me which one the tallest So the computer needst ook at each person in turn, and foreach ont performs atest Ave they taller than the curent alles! person?" Once it has done this foreach person it can give ts answer. rae asc ormocnasmns (8) DEFINING A GOAL & DESIGNING THE SCRIPT Consider how you might approach a different type of script. This example calculates the cost of a name plaque. Customers are charged by the letter. The ist thing you should do is deta your gals for the serot Ghat you wantit to schieve) Customers can have aname added toa plaque: each letter costs $5. When a ser enters aname, show them how much t wil eos Next, break tnt a saris of asks that have tobe performed n order to achieve te gals 1. The sritis triggered when the button sccked. 2tcallecs the name entered int the form fi 3: thehecks thatthe user has entered value 4. the user has not entered anything, message wil appear tling them to enter aname. 5a name hasbeen entered calculate the cost of ‘the sign by multiplying the numberof letters by the cost per letter 6. Show how much the plaque costs. (These numbers correspond with the flowchart on the iaht-hand page) CUSTOM SIGNAGE Enter name: CUSTOM SIGNAGE Enter name: rin ers nnsben ae a CUSTOM SIGNAGE Ls i HOMAS SKETCHING OUT THE TASKS IN A FLOWCHART Often scripts will need to perform different tasks in different situations. You can use flowcharts to work out how the tasks fit together. The flowcharts show the paths between each step. i ‘Get he name eter int the fom t ' Ginn> @ Ccalelate the cost of he son ters rice) t ‘hoy the cout ofthe sl on te sereen ‘Arrows show how the script moves om one task tothe next. The cifferent shapes represent diferent ‘types of tasks. In some places there ave decisions which cause the code to follow eifterent paths. ‘You wil learn how to turn this exampleinto code in Chapter 2. You will also see many more examples of diferent lowchars throughout the book, and you wil meet code that helps you deal wit each of these types of situations, Some experienced programmers use move complex cancal reservations canceled |cancelBooking) | eating 4 rooms a2 werHoD what doce: cam » © | errr conser vane ot rooting roperty | gym tase ‘cancelBookingO) decreases value of bookings sroverty | boat we heckAvalabity()_sbtrct value of Bookings property ‘fom seus of rooms property ana Totus number of eam avBtaDie Ga) THE ABC OF PROGRAMMING HOTEL OBJECT 1. When a reservations made, the book event res 2.The book event riggers the nakeBooking() method, which inreases the value ofthe bookings property 23. The vale ofthe bookings prop \yischangedto rellect how many rooms the hotel has avaiable, ‘OBJECT TYPE: CAR EVENT happens when: method call PROPERTIES brake driverslows down changespoed) | make eww GERI iver speeds up changespecso | QUIEN and closing tag for that web page, and the 1astHodi fied property ofthe dacurent object tells youthe date this page was last update, ‘OBJECT TYPE: WINDOW location. http//mwwiavascripthock com/ PROPERTIES ur. hetes/wurjavascriptook com/ lastModitied 09/04/2014 15:58:57 tile Learn Javascript & jquery ‘Abook that toaches you inanicerway Se aa ne} THE DOCUMENT OBJECT REPRESENTS AN HTML PAGE Using the document object, you can access and change what content users see on the page and respond to how they interact with it Like other objects that represent real-world things, the docunent object has: PROPERTIES Properties describe characteristics of the curent web page (such as the tte ofthe page). METHODS: Methods perform asks associated with the ‘document currently leaded in the browser (such ‘8 geting information rom a specified element or ‘adding pew content) EVENTS You can respond to events, suchas a user clicking tapping onan element @ wenscor ocearne Because all major web browsersimplement the docunent abjectin the same way, the people who ‘reat the browsers hove alrend: ‘© implemented properties that you can access to find out about the curent page in the browser '© Written methods that achieve some common tasks that you are likely to want todo with an HTML page So you wil elearning how to work with this object. Infact the docunent objects just on of set of objects that all mor browsers support. When the browse ereatesamedel ofa web page, tnt oly creates a document object, butt also creates 2 new object foreach element on the page Together these objects ar described inthe Document Object ‘Model, which yu will meetin Chapter 5 HOW A BROWSER SEES A WEB PAGE In order to understand how you can change the content of an HTML Pee Seg ee OL ean Pe ee seas Toa Ce eo Tad create Usa ET ar ad Perna) ead a ee Pe acre mS ag instructions (in JavaScript) into instructions the computer can follow. eee Tee a The bro St) Lo] SUMMARY THE ABC OF PROGRAMMING B: How do computers fit in with the world around them? HOW DO! WRITE A SCRIPT FORA WEB PAGE? HOW HTML, CSS, & JAVASCRIPT FIT TOGETHER Before diving into the JavaScript language, you need to know how it will fit together with the HTML and CSS in your web pages. Web developers usually tak about tvee languages that ar ured to create web pages: HTML, CSS, and JavaScript CONTENT LAYER hte files ‘This is where the content of the page ives. The HTML gives the page structure and adds, semantics, Where posible, am to keep the ‘te languages in separates, with the HTML page linking to CSS and JavaScript fies {css} PRESENTATION LAYER ses fies ‘The CSSenhances the HTML age with ules that statehow the HTML conten is presented ackarounds, borders, box dimensions, colors fonts, te.) Programmer olten lero this 88 separation of concerns Each lanauage forms a separate layer wth citferent purpose, Each ayer, from ett right, bulds on the previous one. javascript () BEHAVIOR LAYER ‘Thisis where we can change how the page behaves, adding interactivity. We wil im to keep ‘as much of our JavaScript as possible in separate es. ‘Asmore and more web-enabled

You might also like