Preview only show first 10 pages with watermark. For full document please download

Javascript And Jquery - Jon Duckett | Java Script | Cascading Style ...

Javascript and Jquery - Jon Duckett - Ebook download as PDF File (.pdf), Text File (.txt) or read book online. JavaScript Book.

   EMBED

  • Rating

  • Date

    June 2017
  • Size

    91.5MB
  • Views

    3,075
  • Categories


Share

Transcript

JAVASCRIPT & JQUERY Interactive Front-End Web Development JON DUCKETT Addit ional material by: GI LLES RUPPERT & JACK MOORE WI.LEY Th.e ttxt stock is SFI ctr1il1~ Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com '')2014 by John W iley & Sons, Inc., Indianapolis, Indiana ISBN:978-l-118-53164-8 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical. photocopying, recording, scanning or otherwise, except as permitted under Sections 107or108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher. or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center. 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc.. 111 River Street. Hoboken, NJ 07030, (201) 748· 6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of W arranty: The publisher and the author make no representations or warranties w ith respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotiona l materiais. The advice and strategies contain ed herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or website may provide or recommendations it may make. Further. readers should be aware that Internet websites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762·2974. outside the United States at (317) 572·3993 or fax (317) 572- 4002. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2013933932 Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book. CREDITS For John Wiley & Sons, Inc. For Wagon Ltd. Executive Editor Carol Long Auth or Jon Duckett Cover Desig n Emme Stone Project Editor Kevin Kent Co-Authors Jack Moore (Chapters 11 & 12) Design Emme Stone Jon Duckett Gilles Ruppert (Chapter 13) Photography John Stewardson johnstewardson. com Product ion Editor Daniel Scribner Editorial M anager Mary Beth Wakefield A ssociat e Director of Marketing David Mayhew Marketing M anager Lorna Mein Business Manager Amy Knies Vice President and Executive Group Publisher Richard Swadley Associate Publisher Jim Minatel Project Coordinat or, Cover Todd Klemme Technical Review Mathias Bynens Review Team Chris Ullman David Lean Harrison Thrift Jay Bursky Richard Eskins Scott Robin Stachu Korick Thank you Annette Loudon M ichael Tomko M ichael Vella Zarb Pam Coca Rishabh Pugalia Illustration Matthew Cencich (Hotel in Chapter 3) Emme Stone (Teacher in Chapter 4) Additional Phot ography Electronics in Chapters 8 & 9: Aaron Nielsen Arkadiusz Jan Sikorski Matt Mets Mirsad Dedovic Steve Lodefink javascriptbook. com/credits This book explains how JavaScript can be used in browsers to make websites more interactive, interesting, and user-friendly. You will also learn about jQuery because it makes writing JavaScript a lot easier. To get the most out of this book, you will need t o know how to bui ld web pages using HTML and CSS. Beyond that. no prior experience with programming is necessary. Learning to program with JavaScript involves: 1 Understanding some basic programming concepts and the terms that JavaScript programmers use to describe t hem. 2 3 Learning the language itself, and, like all languages, you need to know its vocabulary and how to structure your sentences. Becoming famil iar with how it is applied by looking at examples of how JavaScript is commonly used in websites today. The only equipment you need to use this book are a computer with a modern web browser installed, and your favorite code editor, (e.g., Notepad, TextEdit. Sublime Text. or Coda). 0 INTRODUCTION CREATING OBJECTS USING LITERAL NOTATION __ .. _..,._ ____ ... ......... __.,.. ==---'"'""· --· .....,. ...,, ...__... Introduction pages come at the beginning of each chapter. They introduce the key topics you will learn about. ACCESSING ELEMENTS Reference pages introduce key pieces of JavaScript. HTML code is shown in blue, CSS code in pink, and JavaScript in green. .... , ~~~E-:;:.:~ ~·§.?=~ : .._____ -----·· -----..-·-...-..· --------·---------------- ~~;,:?~ __ _ _____ ____ ...._,._ E"":::.:::=:,,;...-==-.... ...,._ ,_....... __,.._,_..___ -------·---- ...... ..,_,,,_,._ ... .. - - -·-·-.-. . .-__ ---·--........... -..·-··-·---_.. _........___ -·---·-.. -··-·- ·-~ -----... _.........--·-··-··-- __ .. ------ - CREATING MORE OBJECT LITERALS Background pages appear on white. They explain the context of the topics covered that are discussed in each chapter. Diagram and infographics pages are shown on a dark background. They provide a simple, visual reference to topics discussed. EXAMPLE ~6.iSO"· -----··- .. ....;-••• --... ____ ___.. .. .........·--· _ .. .·--.-!-= . . ..:. :;.-_-:,.......... :-;--·... ,,....____ ·--·...-..... _ -----·--·.... ..._ ___ Example pages bring together the topics you have learned in that chapter and demonstrate how they can be applied. Summary pages come at the end of each chapter. They remind you of the key topics that were covered in each chapter. INTRODUCT I O N 0 1 ACCESS CONTENT You can use JavaScript to select any element, attribute, or tex t from an HTML page. For example: • Select the text inside all of the elements on a page • Select any elements that have a c 1ass attribute with a value of note • Find out what was entered into a text input whose id attribute has a value of ema i 1 2 MODIFY CO NTENT You can use JavaScript to add elements, attributes, and tex t to the page, or remove them. For example: • Add a paragraph of text after the first element • Change the value of c 1ass attributes to trigger new CSS rules for those elements • Change t he size or position of an element 3 PROGRAM RULES You can specify a set of steps for the browser to follow (like a recipe), which allows it to access or change the content of a page. For example: • • • A gallery script could check which image a user clicked on and display a larger version of that image. A mortgage calculator could collect values from a fo rm, perform a ca lculation, and display repayments. A n animation could check the dimensions of the browser window and move an image to the bottom of the viewable area (also known as the viewport). 4 REACT TO EVENTS You can specify that a script should run when a specific event has occurred. For example, it could be run when: • • • • • • A button is pressed A link is clicked (or tapped) on A cursor hovers over an element Information is added to a form An interval of time has passed A web page has finished loading EXAMPLES OF JAVASCRIPT IN THE BROWSER Being able to cha nge the content of an HTML page w hile 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 t he browser ca n follow React to events triggered by t he user or browser At IH~t OUf dlfb d Jlit~lt1111 ~·'l"h.tl.,kt..)ttllt)• tfff•fllr•4difk)oMllict.. i:Ml.-ldulll)'., . . . 11.... .......nltnrrollr:•\ 0 SLIDESHOWS FORMS Shown in Chapter 11 Shown in Chapter 13 Slideshows can display a number of different images (or other HTML content) w ithin the same space on a given page. They can play automatically as a sequence, or users can click through the slides manually. They allow more content to be displayed within a limited amount of space. Validating form s (checking whether they have been filled in correctly) is important when information is supplied by users. JavaScript lets you alert the user if mistakes have been made. It can also perform sophisticated calculations based on any data entered and reveal the results to the user. React: Script triggered when the page loads Access: Get each slide from the slideshow Modify: Only show the first slide (hide others) Program: Set a timer: w hen to show next slide Modify: Change which slide is shown React: When user clicks button for diffe rent slide Program: Determine w hich slide to show Modify: Show the requested slide React: User presses the submit button when they have entered their name Access: Get value from form field Program: Check that t he name is long enough Modify: Show a warning message if the name is not long enough INTRODUCTION The examples on these two pages give you a taste of what JavaScript can do within a web page, and of the techniques you will be learning throughout this book. In the coming chapters, you will learn how and when to access or modify content, add programming rules, and react to events. < .... ,. .. rolk • Roll up! Roi up! It's the maker bus- ---......... ... °"""'._.........._....... """)OotPf'llfl,,_... . . _ . . , =::.-::-...:.::.~ ,..._.......,. .............. ..... ---. .--:.--:.:.:::· =-~ _.._. .... ~ RELOAD PART OF PAGE FILTERING DATA Shown in Chapter 8 Shown in Chapter 12 You might not want to force visitors to reload the content of an entire web page, particularly if you only need to refresh a small portion of a page. Just reloading a section of the page can make a site feel like it is faster to load and more like an application. If you have a lot of information to display on a page, you can help users find information they need by providing filters. Here, buttons are generated using data in the attributes of the HTML elements. When t he user clicks on one of t he buttons, they are only shown the images with that keyword. React: Script triggered when user clicks on link Access: The link that they clicked on Program: load the new content that was requested from that link Access: Find the element to replace in the page Modify: Replace that content with the new content React: Script triggered when page loads Program: Collect keywords from images Program: Turn the keywords into buttons the user can click on React: User clicks on one of the buttons Program: Find the relevant subset of images that should be shown Modify: Show the subset of images that use that tag INTRODUCTION 0 THE STRUCTURE O F TH IS BOOK In order to teach you JavaScript, this book is divided into two sections: CORE CONCEPTS PRACTICAL A PP LICATI ONS The first nine chapters introduce you to the basics By this point you will already have seen many examples of how JavaScript is used on popular of programming and the JavaScript language. Along the way you will learn how it is used to create more engaging, interactive, and usable websites. websites. This section brings together all of the techniques you have learn ed so far, to give you practical demonstrations of how JavaScript is used Chapter 1 looks at some key concept s in computer programming, showing you how computers create models of th e world using data, and how JavaScript by professional developers. Not only will you see a selection of in-depth examples, you will also learn is used to change the contents of an HTML page. scripts from scratch. more about t he process of designing and w riting Chapters 2-4 cover the basics of the JavaScript Chapter 10 deals with error-handling and debugging, language. and explains more about how JavaScript is processed. Chapter 5 explains how the Document Obj ect Model (DOM) lets you access and change a document's Chapter 11 shows you techniques for creating contents while it is loaded into the browser. Chapter 6 discusses how events can be used to trigger code. Chapter 7 shows you how jQuery can make the content panels-such as sliders, modal windows, tabbed panels, and accordions. Chapter 12 demonstrates several techniques for filtering and sorting data. This includes fil teri ng a gallery of images, and re-ordering the rows of a table by clicking on the column headings. process of writing scripts faster and easier. Chapter 13 deals with form enhancements and how Chapter 8 introduces you to Ajax, a set of to validate fo rm entries. techniques that allow you to just change part of a web page without reloading the entire page. Unless you are already a confident programmer, you Chapter 9 covers Application Programming Interfaces (APls), including new A Pls that are part of HTMLS and those of sites like Google Maps. 0 INTRODUCTION will probably find it helpful to read the book from start to finish the first time. However, once you have grasped the basics, we hope it will con tinue to be a helpful reference as you create your own scripts. BROWSER SUPPORT Some early examples in 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:// j avascri pt book. com). We explain techniques for dealing with older browsers in later chapters. Each version of a web browser adds new features. Often these new features make tasks easier, or are considered better, than using older techniques. But, website visitors do not always keep up with the latest browser releases, so website developers To make JavaScript easier to learn, the first few chapters use some features of JavaScript th at are not supported in IE8. But: • cannot always rely upon the latest technologies. You will learn how to deal with IE8 and older browsers in later chapters (because we know that many clients expect sites to work in IE8). It just requires knowledge of some extra code As you will see, there are many inconsistencies between browsers th at affect JavaScript developers. jQuery will help you deal with cross-browser inconsistencies (it is one of the major reasons w hy jQuery rapidly gained popularity amongst web 8 or requires you to be aware of some additi onal • issues. Online, you w ill find alternatives available for each example that does not work in IE8. developers). But, before you learn jQuery, it helps to But please check the comments in tho se code samples to make sure you know about the about know what it is helping you to achieve. issues involved in using them. INTRODUCTION Before you learn how to read and write the JavaScript language itself, you need to become familiar with some key concepts in computer programming. They will be covered in t hree sections: A B What is a script and how do I crea te one? How do computers fit in with the world around them? C How do I write a script fo r a web page? Once you have learned the basics, t he fo llowing chapters will show how t he JavaScript language can be used to tell browsers what you want them to do. 0 THE ABC OF PROGRAMMING THE ABC OF PROGRAMMING 0 A SCRIPT IS A SERI ES OF INSTRUCTIONS A script is a series of instructions that a computer can follow to achieve a goal. You could compare scripts to any of the following: RECIPES HANDBOOKS MANUALS By fo llowing the instructions in a Large companies often provide handbooks for new employees Mechanics often refer to car recipe, one-by-one in t he order set out, cooks can create a dish repair manuals when servicing models they are not familiar they have never made before. that contain procedures to fo llow in certain situations. Some scripts are simple and only deal with one individual scenario, For example, hotel handbooks may contain steps to follow in along with details of how to fix like a simple recipe for a basic different scenarios such as when any issues th at arise. dish. Other script s can perform many tasks, like a recipe for a complicated three-course meal. a guest checks in, when a room needs to be tidied, w hen a f ire alarm goes off, and so forth. For example, there might be details about how to test the Another similarity is that, if In any of these scenarios, the brakes. If they pass this test, the mechanic can then go on to the you are new to cooking or programming, there is a lot of employees need to follow only the steps for that one new terminology to learn. type of event. (You would not want someone going through every single step in the entire handbook while you were waiting to check in.) Similarly, in a complex script, the browser might use only a subset of the code available at any given time. with. These manuals contain a series of tests to check the key functions of the car are working, next test without needing to fix the brakes. But, if they fail, the mechanic will need to follow the instructions to repair them. The mechanic can then go back and test the brakes again to see if the problem is fixed. If th e brakes now pass the test, th e mechanic knows they are fixed and can move onto the next test. Similarly, scripts can allow the browser to check the current situation and only perform a set of steps if that action is appropriate. G THE ABC OF PROGRAMMING WRITING A SCRIPT To write a script, you need to first state your goal and then list the tasks that need to be completed in order to achieve it. Humans can achieve complex goals without thinking about them too much, for example you might be able to drive a car, cook breakfast, or send an email without a set of detailed instructions. But the first time we do these things they can seem daunting. Therefore, when learning a new skill, we often break it down into smaller tasks, and learn one of these at a time. With experience these individual tasks grow familiar and seem simpler. Some of the scripts you will be reading or writing when you have fin ished t his book will be quite complicated and might look intimidating at first. However, a script is just a series of short instructions, each of which is performed in order to solve the problem in hand. This is why creating a script is like writing a recipe or manual that allows a computer to solve a puzzle one step at a time. It is worth noting, however, that a computer doesn' t learn how to perform tasks like you or I might; it needs to follow instructions every time it performs the task. So a program must give the computer enough detail to perform the task as if every time were its first time. 0 THE ABC OF PROGRAMMING Start with the big picture of what you want to achieve, and break that down into smaller steps. 1: DEFINE THE GOAL First, you need to define the task you want to achieve. You can think of this as a puzzle for the computer to solve. 2: DESIGN TH E SCRIPT To design a script you split the goal out into a series of tasks that are going to be involved in solving this puzzle. This can be represented using a flowchart. You can then write down individual steps that the computer needs to perform in order to complete each individual task (and any information it needs to perform the task), rather like writing a recipe that it can follow. 3: CODE EACH STEP Each of the steps needs to be written in a programming language that the compu ter understands. In our case, this is JavaScript. As tempting as it can be to start coding straig ht away, it pays to spend time designing your script before you start w riting it. THE ABC O F PROGRAMMING 0 FROM STEPS TO CODE Every step for every task shown in a flowchart needs to be written in a language the computer can understand and follow. In thi s book, we are focussing on the JavaScript language and how it is used in web browsers. Just like learning any new language, you need to get to grips wit h the: • • Vocabulary: The words that computers understand Syntax: How you put those words t ogether to create instructions computers can follow A long w ith learning the language itself, if you are new to programming, you will also need to learn how a computer achieves different types of goals using a programmatic approach to problem-solving. Computers are very logical and obedient. They need to be told every detail of what th ey are expected to do, and they will do it w ithout question. Because they need different types of inst ructions compared to you or I, everyone who learns to program makes lots of mistakes at the start. Don't be disheartened; in Chapter 10 you will see several ways to discover w hat might have gone w rong - programmers call t his debugging. e T HE ABC OF PROGRAMMING • l'l o\. I 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 af ter another. The type of instructions t hey need are often different to the type of instructions you might give to another human. Therefore, throughout the book you will not only learn the vocabulary and syntax that JavaScript uses, but you will also learn how to write instructions that computers can follow. For example, when you look at the picture on the left how do you tell which person is the tallest? A computer would need explicit, step-by-step instructi0ns, such as: 1. Find the height of the first person 2 . Assume he or she is the "tallest person" 3 . Look at the height of the remaining people oneby-one and compare their height to the "tallest person" you have found so far 4. At each step, if you fi nd someone whose height is greater t han t he current "tallest person", he or she becomes the new "tallest person" 5. Once you have checked all the people, tell me which one is the tallest So the computer needs to look at each person in turn, and for each one it performs a test ("Are they taller than the current tallest person?"). Once it has done this for each person it can give its answer. THE ABC OF PROGRAMMING G 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 first thing you should do is detail your goals for the script (what you want it to achieve): Customers can have a name added to a plaque; each letter costs $5. When a user enters a name, show them how much it will cost. CUSTOM S I GNAG E Enter name: Next, break it into a series of tasks that have to be performed in order to achieve the goals: 1. The script is triggered when t he button is clicked. 2. It collects the name entered into the form field. 3. It checks that the user has entered a value. 4. If the user has not entered anyt hing, a m essage will appear telling them to enter a name. 5. If a name has been entered, calculate th e cost of the sign by multiplying the number of letters by the cost per letter. 6. Show how much the plaque costs. (These numbers correspond with th e flowchart on the right-hand page.) CU STOM SIGNAG E Enter name: Please enter a name below... ( THOMAS 11!.iild·E* CUSTOM S I GNAG E Ill @ THE ABC OF PROGRAMM ING 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. 0 When the button has been clicked e Get the name entered into the form Arrows show how the script moves from one task to the next. The different shapes represent diff€rent I types of tasks. In some places there are decisions which cause the code to fol low different paths. • I e ' You will learn how to turn this example into code in Is there a name to get? Chapter 2. You w ill also see many more examples of different flowcharts throughout the book, and you w ill meet code that helps you deal w ith each of these I 0 Ask user the user to enter a name types of situations. 0 Calculate the cost of the sign (letters x price) Some experienced programmers use more complex diagram styles that are specifically designed to 9 Show the cost of the sign on the screen • I represent code - however, they have a steeper learning curve. These informal flowcharts will help you understand how scripts work while you are in the process of learning the language. FLOWCHART KEY Generic step Event Input or output Decision THE ABC OF PROGRAMMING @ A script is a series of instructions that the computer can follow in order to achieve a goal. Each time the script runs, it might only use a subset of all the instructions. Computers approach tasks in a different way than humans, so your instructions must let the computer solve the task prggrammatically. To approach writing a script, break down your goal into a series of tasks and then work out each step needed to complete that task (a flowchart can help). THE ABC OF PROGRAMMING @ COMPUTERS CREATE MODELS OF THE WO RLD USING DATA Here is a model of a hotel, along wit h some model trees, model people, and model cars. To a human, it is clear what kind of real -world object each one represents. --· QUAY H 0 @ THE ABC OF PROGRAMMING T E L A computer has no predefined concept of what a hotel or car is. So how do we use computers to create hotel booking apps, Programmers make these models using data. That is not It does not know w hat they are used for. Your laptop or phone will not have a favorite brand of or video games where players can race a car? The answer is that programmers create a as strange or as scary as it sounds because the data is all t he computer needs in order to car, nor will it know what star rating your hotel is. very different kind of model, especially for computers. fol low the instructions you give it to carry out its tasks. OBJECT TYPE: HOTEL OBJECT TYPE: CAR THE ABC OF PROGRAMMING 0 OBJECTS & PROPERTIES If you could not see the picture of the hotel and cars, the data in the information boxes alone would still tell you a lot about this scene. OBJECTS (TH INGS) PROPERTIES (CHA RACTERISTICS) In computer programming, each physical thing in Both of the cars share common characteristics. In fact, all cars have a make, a color, and engine the world can be represented as an object. There are two different types of objects here: a hotel and a car. Programmers might say that there is one inst ance of size. You could even determine their current speed. Programmers call these characteristics the properties of an object. the hotel object, and two instances of the car object. Each property has a name and a value, and each of Each object can have its own: these name/value pairs tells you something about • Properties each individual instance of the object. • Events • Methods Together t hey create a working model of that object. The most obvious property of thi s hotel is its name. The value for that property is Quay. You can tell the number of rooms the hotel has by looking at the value next to the rooms property. The idea of name/value pairs is used in both HTML and CSS. In HTML, an attribute is like a property; different attributes have different names, and each attribute can have a value. Similarly, in CSS you can change the color of a heading by creating a rule that gives the col or property a specific value, or you can change the typeface it is written in by giving the font-family property a specific value. Name/value pairs are used a lot in programming. @ THE ABC OF PROGRAMMING HOTEL OBJECT CAR OBJECTS The hotel object uses property names and values to tell you about this particular hotel, such as the hotel's name, its rating, the number of rooms it has, and how many of these are booked. You can also tell whether or not this hotel has certain facilities. The car objects both share the same properties, but each one has different values for those properties. They tell you the make of car, what speed each car is currently traveling at, what color it is, and what type of fuel it requires. OBJECT TYPE: HOTEL PROPERTIES name Quay rating 4 ro o ms 42 bookings 21 gym false pool true PRO PERTIES currentSpeed PROPERTIES BMW make Porsche 30mph currentSpeed 20mph silver color silver gasoline THE ABC OF PROGRAMMING § EVENTS In the real world, people interact with objects. These interactions can change the values of the properties in these objects. WHAT IS AN EVENT? WHAT DOES AN EVENT DO? There are common ways in which people interact with each type of object. For example, in a car a driver will typically use at least two pedals. The car has been designed to re spond differently w hen the driver interacts with each of the different pedals: Programmers choose which event s they respond to. When a specific event happens, that event can be used to trigger a specific section of the code. • The accelerator makes the car go faster • The brake slows it down Similarly, programs are designed to do different things when users interact with the computer in different ways. For example, clicking on a contact li nk on a web page could bring up a contact form, and entering text into a search box may automatically trigger the search functionality. An event is the computer's way of sticking up its hand to say, "Hey, this just happened!" @ THE ABC OF PROGRAMMING Scripts often use different events to trigger different types of functionality. So a script will state which events the programmer wants to respond to, and what part of t he script should be run when each of t hose events occur. HOTEL OBJECT CAR OBJECTS A hotel w ill regularly have bookings for rooms. Each time a room is reserved, an event called book can be used to trigger code that will increase the value of the bookings property. Likewise, a cancel event can trigger code that decreases the value of the bookings property. A driver will accelerate and brake throughou t any car journey. An accelerate event can trigger code to increase the value of the currentSpeed property and a brake event can trigger code to decrease it. You will learn about the code that responds to the events and changes these properties on the next page. OBJECT TYPE: HOTEL EVENT happens when: book reservatio n is made cancel reservation is cancelled happens when: · driver slows down happens when: driver slows down driver speeds up THE ABC OF PROGRAMMING G METHODS Methods represent things people need to do with objects. They can retrieve or update the values of an object's properties. @ WHAT IS A METHOD? WHAT DOES A METHOD DO? Methods typically represent how people (or other things) interact with an object in the real world. The code for a method can contain lots of instructions that together represent one task. They are like questions and instruction s that: When you use a method, you do not always need to know how it achieves its task; you just need to know how to ask the question and how to interpret any answers it gives you. • Tell you something about that object (using information stored in its properties) • Change t he value of one or more of that object's properties T HE ABC OF PROGRAMMING HOTEL OBJECT CAR OBJECTS Hotels will commonly be asked if any rooms are free. The value of the currentSpeed property needs to go up and down as the driver accelerates and brakes. The code to increase or decrease the value of the currentSpeed property could be written in a method, and that method could be called changeSpeed (). To answer this question, a method can be written that subtracts the number of bookings from the total number of rooms. Methods can also be used to increase and decrease the value of the bookings property when rooms are booked or cancelled. OBJECT TYPE: HOTEL METHOD makeBooking() ............ .... .... . cancel Booking() checkAvailability() METHOD what it does: increases value of bookings p roperty ............................... .,_,,,................. . .............. i decreases value of bookings property subtracts value of bookings property from value of rooms property and returns number of rooms available what it does: changeSpeed() ; increases or decreases value of currentSpeed property METHOD what it does: changeSpeed() · increases or decreases value of currentSpeed property THE ABC OF PROGRAMMING @ PUTTING IT ALL TOGETHER Computers use data to create models of things in the real world. The events, methods, and properties of an object all relate to each other: Events can trigger methods, and methods can retrieve or update an object's properties. EVENT cancel happens when: method called: PROPERTIES reservation is made make Booking() name Quay rating 4 reservation is cancelled ' cancel Booking() rooms METHOD f) what it does: ' increases value of bookings property cancel Booking() !. ?ecreases value of .~ooking:. P.ropert·y·· 1.. ·1·1·1:11.r-n '-·-·-······· 42 22 gym false pool true checkAvailabilityO : subtracts value of bookings property l from value of rooms p roperty and returns number of rooms available QUAY H 0 @ THE ABC OF PROGRAMMING T E L HOTEL O BJ ECT CAR O BJ ECTS 1. When a reservation is made, the book event fires. 2 . The book event triggers the makeBooki ng () method, which increases the value of the bookings property. 3. The value of the bookings property is changed to reflect how many rooms the hotel has available. 1. As a driver speeds up, the accel erate event fires. 2 . The accelerate event calls the changeSpeed () method. which in turn increases the value of the currentSpeed property. 3. The value of the currentSpeed property reflects how fast the car is traveling. OBJECT TYPE: CAR EVENT fii§§§t§tit!i METHOD happens when: method called: PROPERTIES driver slows down ' changeSpeed() make BMW driver speeds up current Speed 45mph color silver fuel diesel \ changeSpeed() what it does: e changeSpeed() i increases o r decreases value : of currentSpeed property THE ABC OF PROGRAMMING @ WEB BROWSERS ARE PROGRAMS BUILT USING OBJECTS You have seen how data can be used to create a model of a hotel or a car. Web browsers create similar models of the web page they are showing and of the browser window that the page is being shown in. @ WINDOW OBJECT DOCUMENT OBJECT On the right-hand page you can see a model of a computer with a browser open on the screen. The current web page loaded into each window is modelled using a document object. The browser represents each window or tab using a window object. The location property of the window object w ill tell you the URL of the current page. The title property of the document object tells you what is between the opening and closing tag for that web page, and the l astModi f i ed property of the document object tells you the date this page was last updated. TH E ABC OF PROGRAMMING OBJECT TYPE: WINDOW PROPERTIES location http://www.javascriptbook.com/ • PROPERTIES http://www.javascriptbook.com/ lastModified 09/04/2014 15:33:37 Learn JavaScript & jQuery A book that teaches you in a nicer way 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, Because all major web browsers implement th e the document object has: document object in the same way, the people who create the browsers have already: PROPERTIES • Properties describe characteristics of the current web page (such as the t itle of the page). METHODS Methods perform tasks associated with the document currently loaded in th e browser (such as getting information from a specified element or adding new content). EVENTS You can respond to events, such as a user clicking or tapping on an element. @ THE ABC OF PROGRAMMING • Implemented properties that you can access to find out about the current page in the browser Written methods that achieve some common tasks that you are likely to want to do with an HTML page So you will be learning how to work with this object. In fact, the document object is just one of a set of objects that all major browsers support. When the browser creates a model of a web page, it not only creates a document object , but it also creates a new object for each element on the page. Together these objects are described in the Document Object Model, which you will meet in Chapter 5. PROPERTIES http://www.javascriptbook.com/ lastModified 09/04/2014 15:33:37 Learn JavaScript & jQuery A book that teaches you in a nicer way EVENT happens when: page and assets have finished loading user clicks the mouse over the page , user presses down on a key METHOD what it does: adds new content to the document getElementByld() accesses an element when you state its id attribute HOW A BROWSER SEES A WEB PAGE In order to understand how you can change the content of an HTML page using JavaScript, you need to know how a browser interprets the HTML code and applies styling to it. 1: RECEIVE A PAGE AS HTML CODE 2: CREATE A MODEL OF THE PAGE AND STORE IT IN MEMORY 3: USE A RENDERING ENGINE TO SHOW THE PAGE ON SCREEN Each page on a website can be seen as a separate document . So, the web consists of many sites, each made up of one or more documents. The model shown on the right hand page is a representation of one very basic page. Its structure is reminiscent of a family tree. At the top of the model is a document object, which represents the whole document. If there is no CSS, the rendering engine will apply default styles to HTML elements. However, the HTML code for this example links to a CSS style sheet, so the Beneath the document object each box is called a node. Each of these nodes is another object. This example features three types of nodes representing elements, text within the elements, and attribute. browser requests that file and displays the page accordingly. When the browser receives CSS rule s, t he rendering engine processes them and applies each rule to its corresponding elements. This is how the browser positions the elements in the correct place, with the right colors, fonts, and so on. All major browsers use a JavaScript interpreter to translate your instructions (in JavaScript) into instructions the computer can follow. When you use JavaScript in the browser, there is a part of the browser that is called an interpreter (or scripting engine). 40 THE ABC OF PROGR A MM IN G The interpreter takes your instructions (in JavaScript) and translates them into instructions the browser can use to achieve the tasks you want it to perform. In an interpret ed programming language, like JavaScript. each line of code is translated one-by-one as the script is run. Constructive & Co. 'EJl9.Kl A~CHlffCTUUI M OOEIS l'or •ll order• an4 iAquirioa pleaee call 5SS-l3tt THE ABC OF PROGRAMMING @ 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 talk Where possible, aim to keep th e Each language forms a separate about three languages that are used to create web pages: HTML, CSS, and JavaScript. three languages in separate fi les, with the HTML page linking to CSS and JavaScript files. layer with a different purpose. Each layer, from left to right. builds on the previous one. {css} avascri pt() CONTENT LAY ER PRESENTATION LAYER BEHAVIOR LAYER . html files . css files .js files This is where th e content of The CSS enhances t he HTML page with rules that state how This is w here we can change the page lives. The HTML gives the page struct ure and adds semantics. the HTML content is presented (backgrounds, borders, box dimensions, colors, fonts, etc.). Programmers often refer to this as a separation of concerns. 8 j THE ABC OF PROGRAMMING how the page behaves, adding interact ivity. We will aim to keep as much of our JavaScript as possible in separate files. PROGRESS IVE ENHAN CE MENT These three layers form the basis of a popular approach to building web pages called progressive enhancement. As more and more web-enabled devices come onto the market, this concept is becoming more widely adopted. It's not just screen sizes that are varied - connection speeds and capabilities of each device can also differ. Also, some people browse wi th JavaScript turned off, so you need to make sure that the page still works for them. Constructive & Co. For all orders and inquiries please call 555-3344 Constructive & Co. Constructive & Co. tflrOKE AICHtJf CTU•Al MOQEU IUPOJCC AICHlf fClUIAl MODEU ror a.11 order• and J.nquirie s please call 555-3364 GOOD AFTERNOON! ror al.l orde rs a.ad iaquiri•• pl•••• call 555- 31•• HTML ONLY Starting with the HTML layer allows you to focus on th e most HTML+CSS HTML+CSS+JAVASCRIPT Adding the CSS rules in a The JavaScript is added last important thing about your site: separate fi le keeps rules regardi ng how the page looks and enhances the usability of the page or the experience of its content. away from the content itself. interact ing with the site. Being plain HTML, this layer You can use the same style sheet Keeping it separate means should work on all kinds of devices, be accessible to all with all of your site, making your sites faste r to load and easier that the page still works if the user cannot load or run the users, and load quite quickly on slow connections. to maintain. Or you can use different style sheets with the JavaScript. You can also reuse the code on severa l pages (making the site faster to load same content to create different views of the same data. and easier to maintain). THE ABC OF PROGRAMMING @ CREATING A BAS IC JAVASCRIPT JavaScript is written in plain text, just like HTML and CSS, so you do not need any new tools to write a script. This example adds a greeting into an HTML page. The greeting changes depending on the time of day. 0 Create a fold er to put the example in called cOl, then start up your favorite code editor, and enter the text to the right. A JavaScript fi le is just a text file (like HTML and CSS files are) but it has a . j s file extension, so save this file with the name add-content . j s Don't worry about what the code means yet. for now we will focus on how the script is created and how it fits with an HTML page. var today= new Date(); var hourNow = today.getHours(); var greeting ; if (hourNow > 18) { greeting= 'Good evening!'; else if (hourNow > 12) { greeting = ' Good afternoon!'; else if (hourNow > 0) { greeting = 'Good morni ng!'; else { greeting = 'Welcome! ' ; document .write( '

' +greeting + ' '); 8 Get the CSS and images for this example from the website that accompanies the book: www.javascriptbook. com t_ To keep the files organized, in the same way that CSS fil es of ten live in a folder called styles or css, your JavaScript files can live in a folde r called scripts,javascript,orjs. In t his case, save your file in a folder called j s 8 THE ABC OF PROGRAMMING add-content.htmt • WI css !! COi.CU • QI images ..:. construalw -backdrop.Jpg :.... construalve-1090.yif • lndtx.html .. ~ jS HTMl Folder css Folder JPEC lmoge GIFl~t HTML Folder Here you can see the file structure that you will end up with when you finish the example. Always treat file names as being case-sensitive. LINKING TO A JAVASCRIPT FILE FROM AN HTML PAGE When you want to use JavaScript with a web page, you use the HTML tags (but it is better to put scripts in their own fil es). Constructive & Co.
  • Constructive & Co.

    For all orders and inquiries please call 555-3344 f) Finally, try opening the HTM L file, removing the src attribute from the opening tag. The s re attribute is no longer needed because the JavaScript is in the HTML page. As noted on p44, it is better not to mix JavaScript in your HTM L pages like this, but it is mentioned here as you may come across this technique. 0 Open the HTML file in your web browser and the welcome greeting is written into the page. Constructive & Co. IEStOl(E AICHITCCTUf.U MODUS WELCOME! P'or all order• pl..•••• and i.nqui_riea call 555- 33'' As you may have guessed, document. write() writes content into the document (the web page). It is a simple way to add content to a page, but not always t he best. Chapter 5 discusses various ways to update the content of a page. THE ABC OF PROGRAMMING 8 JAVASCRIPT RUNS WHERE IT IS FOUND IN THE HTML When the browser comes across a Note how the CUSTOM SIGNAGE:: Preview: IM I O ~ N I T m AIG u E ~ 1 H olu s E Note t hat t he numbers are not written inside quotation marks. Once a value has been assigned to a variable, you can use the variable name to represent that value (much like you might have done in algebra). Here, the total cost is calculated by multiplying the price of a single tile by t he number of tiles t he customer wants. The result is then w rit ten into the page on the final two lines. You see this technique in more detail on p194 and p216. The first of these two lines finds the element whose id attribute has a value of cost, and the final line replaces the content of that element with new content. Note: There are many ways to write content into a page, and several places you can place your script. The advantages and disadvantages of each technique are discussed on p226. This technique will not work in IE8. BASIC JAVASCRIPT IN STRUCTIONS @ US ING A VARIABLE TO STORE A STRING For the moment, concentrate on the first four lines of JavaScript. Two variables are declared (username and message), and they are used to hold strings (the user's name and a message for that user). The code to update t he page (shown in the last four lines) is discussed fully in Chapter 5. This code selects two elements using the values of t heir id attributes. The text in those elements is updated using the values stored in these variables. Not e how the string is placed inside quote marks. The quotes can be single or double quotes, but they must match. If you start with a single quote, you must end with a single quote, and if you start with a double quote, you must end with a double quote: 0 0 0 "hello' 'hello' 0 'hello" "hello" Quotes should be straight (not curly) quotes: 0 1111 0 "" 0 I I 0 (' Strings must always be written on one line: O 'See our upcoming range' 0 'See our upcoming range' @ BASIC JAVASCRIPT IN STRUCTIO NS c02/js/string-variable.js JAVA SCRIPT var username; var message; username = 'Molly'; message = 'See our upcoming range'; var elName = document.getElementByld{'name'); elName .textContent = username; var elNote = document .getElementByld( 'note'); elNote .textContent = message; c02/ string-variable.html Elderflower

    Howdy friend !
    Take a l ook around . . .
    W:ii&ll USING QU OTES INSIDE A STRING JAVASCRIPT c02/ js/ string-with-quotes.js var title; var message; title= "Molly's Special Offers" ; message = '25% off l' ; var elTitle = document.getElementByld('title') ; elTitle.innerHTML =title ; var elNote = document.getElementByid ('note') ; elNote.innerHTML =message; M:ii&fl c02/ string-with-quotes .html Elderflower
    Special Offers
    Sign-up to receive personalized offers!
  • Sometimes you will want to use a double or single quote mark within a string. Because strings can live in single or double quotes, if you just want to use double quotes in the string, you could surround the entire string in single quotes. If you just want to use single quotes in the string, you could surround the string in double quotes (as shown in the third line of this code example). You can also use a technique called escaping the quotation characters. This is done by using a backwards slash (or "backslash") before any type of quote mark that appears within a string (as shown on the fourth line of this cod e sample). lijJiliil The backwards slash tells the interpreter that the following character is part of the string, rather than the end of it. Techniques for adding content to a page are covered in Chapter 5. This example uses a property called i nnerHTML to add HTML to the page. In certain cases, this property can pose a security risk (discussed on p228 - p231). BASIC JAVASCRIPT INSTRUCTIONS @ USING A VARIABLE TO STORE A BOOLEAN A Boolean variable can only have a value of true or fa 1se, but this data type is very helpful. In the example on the right, the values true or fa 1se are used in the cl ass attributes of HTML elements. These values trigger different CSS class rules: true shows a check, fa 1se shows a cross. (You learn how the class attribute is set in Chapter 5.) It is rare that you would want to write the words true or false into the page for the user to read, but this data type does have two very popular uses: First, Booleans are used when the value can only be true/ fa 1se. You could also think of these values as on/off or 0/1: true is equivalent to on or 1, fa 1se is equivalent to off or 0 c02/js/boolean-variable. js JAVASCRIPT var i nStock; var shipping; inStock = true; shipping= fa l se; var elStock = document.getElementByld('stock'); elStock.className = inStock; var el Ship = document .getElementByid('shipping'); elShip.className = sh ipping ; lllli~l!!il c02/boolean-variable.html Elderflower
    Available:
    Shipping: ~/span>
    Second, Booleans are used when your code can take more than one path. Remember, different code may run in different circumstances (as shown in the flowcharts throughout the book). ' I test is performed ' I The path the code takes depends on a test or condition. @ BASIC JAVASCRIPT INSTRUCTIONS Available: O Shipping: 0 SHORTHAND FOR CREATING VARIABLES c02/js/shorthand-variable.js JAVASCRIPT CD var price = 5; var quantity = 14; var total = price * quantity; Programmers sometimes use shorthand to create variables. Here are three variations of how to declare variables and assign them values: 1. Variables are declared and values assigned in the same (3) var price, quantity, total ; statement. price = 5; quanti t y = 14 ; total = pr ice * quantity; @ var price var total 2 . Three variables are declared on the same line, then values assigned to each. 3. Two variables are declared and assigned values on the same 5, quantity = 14; price * quantity; line. Then one is declared and assigned a value on the next line. @) // Write total into the element with i d of cost var el = document . getElementBy l d( ' cost'); el . textCont ent = '$' +total; l;!Jiliii (The third example shows two numbers, but you can declare variables that hold different types of data on the same line, e.g., a string and a number.) 4 . Here, a variable is used to hold a reference to an element in the HTML page. This allows you to work directly with the element stored in t hat variable. (See more about this on p190.) While the shorthand might save CUS T OM SIG NAGt m IM0 N T A G !L E ~ 1H 0 us E you a little bit of typing, it can make your code a little harder to follow. So, when you are starting off, you will find it easier to spread your code over a few more lines to make it easier to read and understand. BASIC JAVASCRIPT INSTRUCTIONS @ CHANGING THE VALUE OF A VARIABLE Once you have assigned a value to a variable, you can then change what is stored in the variable later in the same script. Once the variable has been created, you do not need to use the var keyword to assign it a new value. You just use the variable name, the equals sign (also known as t he assignment operator), and the new value for that attribute. For example, the value of a shipping variable might start out as being false. Then something in the code might change the ability to ship t he item and you could therefore change the value to true. In t his code example, the values of the two variables are both swapped from being true to false and vice versa. @ BASIC JAVASCRIPT IN STRUCTIONS c02/js/update-variable.js JAVASCR I PT var inStock; var shipping; inStock = true; shipping = false; /* Some other processing might go here and , as a resul t , the script might need to change t hese values */ inStock = false; shipping = true; var elStock = document.getElementByld('stock'); elStock .className = inStock; var elShip = document .getElementByld('shipping'); elShip .className = shipping; 19Jillil RULES FO R NAMIN G VARIA BLES Here are six rules you must always follow when giving a variable a name: 1 2 3 The name must begin with The name can contain letters, You cannot use keywords or a letter, dollar sign ($),or an underscore (_). It must not start numbers, dollar sign ($), or an underscore (_). Note that you must not use a dash(-) or a reserved words. Keyword s with a number. period (.) in a variable name. are special words that tell the interpreter to do something. For example, var is a keyword used to declare a variable. Reserved words are ones t hat may be used in a future version of JavaScript. ONLINE EXTRA View a full list of keywords and reserved words in JavaScript. 4 All variables are case sensitive, so score and Score would be 5 6 Use a name that describes the If your variable name is made different variable names, but it is bad practice to create two kind of information that the variable stores. For example, fi rstName might be used to up of more than one word, use a capital letter for the first letter of variables t hat have the same name using different cases. store a person's first name, l astNarne for t heir last name, and age for their age. every word after the first word. For example, f i rstName rather than fi rstnarne (this is referred to as camel case). You can also use an underscore between each word (you cannot use a dash). BAS IC JAVASCRIPT INSTRUCTIONS @ ARRAYS An array is a special type of variable. It doesn't just store one value; it stores a list of values. You should consider using an For example, an array can be As you will see on the next page, array whenever you are working suited to storing the individual items on a shopping list because values in an array are separated by commas. with a list or a set of values that are related to each other. it is a list of related items. Arrays are especially helpful Additionally, each time you write when you do not know how many items a list will contain a new shopping list, the number of items on it may differ. because, when you create the array, you do not need to specify how many values it will hold. If you don't know how many items a list will contain, rather than creating enough variables for a long list (when you might only use a small percentage of them), using an array is considered a better solution. In Chapter 12, you will see that arrays can be very helpful when representing complex data. CREATING AN ARRAY c02/js/array-li t eral .js JAVA SCRIPT var colors; colors ['white', 'black', ' custom ' ]; var el document.getElementByld('col ors'); el . textContent = col ors[O]; You create an array and give it a name just like you would any other variable (using the var keyword followed by the name of the array). The values are assigned to t he array inside a pair of square brackets, and each value is separated by a comma. The values in the array do not need to be the same data type, so you 1;1Jill51 can store a string, a number and a Boolean all in the same array. This technique for creating an array is known as an array literal. It is usually the preferred method for creating an array. You can also write each value on a separate line: colors= ['white', 'black', 'custom']; c02/ js/array-constructor.js JAVASCRIPT var colors new Array('white ' , 'black', 'custom ' ); var el = document.getElementByid( ' co lors ' ); el.innerHTML = colors.item(O); On the left, you can see an array created using a different technique called an array constructor. This uses the new keyword fo llowed by Array(); The values are then specified in parentheses (not square brackets), and each value is separated by a comma. You can The array literal (shown in the first code sample) is preferred over the array constructor when creating arrays. also use a method called i tern() to retrieve data from the array. (The index number of the item is specified in the parentheses.) BASIC JAVASCRIPT INSTRUCTIONS G VALU ES IN ARRAYS Values in an array are accessed as if they are in a numbered list. It is important to know that the numbering of this list starts at zero (not one). NUMBERING ITEMS IN AN ARRAY ACCESSING ITEMS IN AN ARRAY NUMBER OF ITEMS IN AN ARRAY Each item in an array is automatically given a number called an index. This can be used to access specific items in the array. Consider the following array which holds three colors: To retrieve the third item on the list, the array name is specified along with the index number in square brackets. Each array has a property called length, which holds the number of items in the array. var col ors ; colors= [' whi te ' , 'black ' , ' custom ']; Here you can see a variable called i temThree is declared. Its value is set to be the third color from the co1ors array. Confusingly, index values start at 0 (not 1), so the following table shows items from the array and their corresponding index values: INDEX VALUE o 'white ' 'bl ack' 2 ' custom' var itemThr ee; itemThree = col ors [ 2] ; Below you can see that a variable called numCo 1ors is declared. Its value is set to be the number of the items in the array. The name of the array is followed by a period symbol (or full stop) which is then followed by the 1ength keyword. var numColors ; numColors =col ors. length ; Throughout the book (especially in Chapter 12) you meet more features of arrays, which are a very flexible and powerful feature of JavaScript. 0 BASIC JAVASCRIPT INSTRUCTIONS ACCESSING & CHANG ING VALUES IN AN ARRAY c02/ js/ update-array.js JAVASCRIPT II Create the array var colors = ['white', 'black' , 'custom']; II Update the third item in the array The first lines of code on the left create an array containing a list of three colors. (The values can be added on the same line or on separate lines as shown here.) Having created the array, the third item on the list is changed colors[2] = 'beige ' ; from 'custom' to 'beige'. II Get the element with an id of col ors To access a valu e from an array, after the array name you specify the index number for that value var el = document .getElementByid(' colors') ; II Replace with third item from the array el .textContent = colors[2]; inside square brackets. You can change the value of an item an array by selecting it and assigning it a new value just as l;IJiiJll you would any other variable (using the equals sign and the new value for that item). In the last two statements, the newly updated third item in the array is added to the page. Color: beige If you wanted to write out all of the items in an array, you would use a loop, which you will meet on p170. BASIC JAVASCRIPT INSTRUCTIONS @ EXPRESSIONS An expression evaluates into (results in) a single value. Broadly speaking there are two types of expressions. 2 1 EXPRESS IO NS THAT JUST ASSIGN A VALUE TO A VAR IABLE EXPRESSIONS THAT USE TWO OR MORE VALUES TO RETURN A SINGLE VALUE In order for a variable to be useful, it needs to be given a value. As you have seen, t his is done using You can perform operations on any number of individual values (see next page) to determine a the assignment operator (the equals sign). single value. For example: var color = 'beige'; var area = 3 * 2; The value of co1or is now beige. The value of area is now 6. When you fi rst decl are a variable using th e var keyword, it is given a special value of undefined. Here the expression 3 * 2 evaluates into 6. This example also uses th e assignment operator, so the This will change when you assign a value to it. Technically, undefined is a data type like a number, result of the expression 3 * 2 is stored in the variable called area. string, or Boolean. Another example where an expression uses two values to yield a single valu e would be where two strings are joined to create a single string. @ BASIC JAVASCRIPT INSTRUCTIONS OPERATORS Expressions rely on things called operators; they allow programmers to create a single value from one or more values. Covered in this chapter: Covered in Chapter 4: ASSIGNMENT OPERATORS COMPARISON OPERATORS A ssign a value to a variable Compare two values and return true or fa 1se color = 'beige'; buy = 3 The value of co 1or is now beige. (See p61) The value of buy is fa 1se. (See p150) AR ITHMETI C OPERATORS LOGICAL OPERATORS Perform basic math Combine expressions and return true or fa 1se area = 3 * 2; buy= (5 The value of area is now 6. (See p76) The value of buy is now true. (See p156) 5; > > 3) && (2 < 4); STRING OPERATORS Combine two strings greeting= 'Hi 1 + 'Mol ly'; The value of greeting is now Hi Molly. (See p78) BASIC JAVA SCRIPT INSTRUCTION S @ ARITHMETI C OPERATORS JavaScript contains the following mathematical operators, which you can use with numbers. You may remember some from math class. NAME ADDITION OPERATOR PURPOSE & NOTES EXAMPLE RESULT + Adds one value to another 10 + 5 15 Subtracts one value from another 10 - 5 5 I 2 SUBTRACTION DIVISION I Divides two values 10 MULTIPLICATION * Multiplies t wo values using an asterisk (Note that this is not the letter x) 10 * 5 50 Adds one to the current number i = 10; i++; 11 Subtracts one from the current number i = 10; i--; 9 Divides two values and returns the remainder 10 % 3 1 INCREMENT . . ++ . . . ... ······-······ ........... ... ....................................... .. ... . ................................................................................... DECREMENT MODULUS % 5 ORDER OF EXECUTION Several arithmetic operations can be performed in one expression, but it is important to understand how the result will be calculated. Multiplication and division are performed before addition or subtraction. This can affect the number that you expect to see. To illustrate this effect, look at the following examples. G Here t he numbers are calculated left to right, so the total is 16: total = 2 + 4 + 10; BASIC JAVASCRIPT INSTRUCTIONS But in the following.example the total is 42 (not 60): total 2 + 4 * 10; To change the order in which operations are performed, place the calculation you want done first inside parentheses. So for the following, the total is 60: total = (2 + 4) * 10; = This is because multiplication and division happen before addition and subtraction. The parentheses indicate that the 2 is added to the 4, and then the resulting figure is multiplied by10. USING ARITHMETIC OPERATORS JAVASCRIPT var subtotal var shipping var total c02/js/arithmetic-operator.js (13 + 1) * 5; 0.5 * (13 + 1) ; II Subtotal is II Shipping i s 70 7 subtotal + shipping ; II Total is 77 var el Sub document .getElementBy id(' subtotal ') ; elSub . textContent =subtotal ; var elShip = document .getElement Byi d('shi ppi ng ') ; elShip.textContent =shipping; var elTotal = document .getElementByid('total '); elTotal . textContent =total; This example demonstrates how mathematical operators are used with numbers to calculate the combined values of two costs. The first couple of lines create two variables: one to store the subtotal of the order, the other to hold the cost of shipping the order; so the variables are named accordingly: subtotal and shipping. On the third line, the total is calculated by adding together these two values. This demonstrates how the mathematical operators can use variables that represent numbers. (That is, the numbers do not need to be written explicitly into the code.) •0•1111• The remaining six lines of code write the results to the screen. Subtotal: $70 Shipping: $7 Grandtotal: $77 BASIC JAVASCRIPT INSTRUCTIONS G STRING OPERATOR There is just one string operator: the+ symbol. It is used to join the strings on either side of it. There are many occasions where you may need to join two or more strings to create a single value. Programmers call the process of joining together two or more strings to create one new string concatenation. For example, you might have a first and last name in two separate variables and want to join them to show a ful l name. In this example, the variable called full Name would hold the string 'Ivy Stone'. var firstName = 'Ivy ' ; var lastName = ' Stone' ; var ful l Name = f irstName + l astName ; MIXING NUMBERS AND STRINGS TOGETHER When you place quotes around @ a num~er, it is a string (not a numeric data type), and you cannot perform addition operations on strings. If you try to add a numeric data type to a string, then the number becomes part of the string, e.g., adding a house number to a street name: If you try to use any of the other arithmetic operators on a string, then the value that results is usually a value called NaN. This means "not a number." var cost l = '7'; var cost2 = '9 ' ; var total = costl + cost2 ; var number = 12; var street= 'Ivy Road'; var add = number + street ; var scor e= ' seven '; var score2 = ' nine'; var total = score * score2 ; You would end up with a string saying '79'. You would end up with a string saying '12Ivy Road' . You would end up with the value NaN. BASIC JAVASCRIPT INSTRUCTIONS USING S'T RING OPERATORS c02/js/string-opera tor.js JAVASCRIPT var greeting= 'Howdy '; var name= 'Mol l y' ; var welcomeMessage = greeting+ name+ '!'; var el = document.getElementByld('greeting'); el .textContent = welcomeMessage; c02/string-operator.html W:iiMfi Elderflower
    Hello friend !
    This example will display a personalized welcome message on the page. The first line creates a variable called greeting, which stores the message for the user. He~e the greeting is the word Howdy. The second line creates a variable that stores the name of the user. The variable is called name, and the user in this case is Molly. The personal welcome message is created by concatenating (or joining) these two variables, adding an exclamation mark, and storin g them in a new variable called we1comeMessage. Look back at the greeting variable on the first line, and note how there is a space after the word Howdy. If the space was omitted, the value of we 1comeMessage would be "HowdyMol ly!" l;IJillii Howdy Molly! BASIC JAVASCRIPT INSTRUCTIONS @ Howdy Molly, please check your order: Custom sign: Total tiles: Subtotal : Shipping: Grand total : M-Ontague House 14 $70 $7 $77 EXAMPLE BASI C JAVASCRIPT INSTRUCTIONS c02/example.html 1111.,.•, JavaScript & jQuery - Chapter 2: Basic JavaScript Instructions Example</ title> <link rel="stylesheet" href="css/c02.css" / > </head> <body> <hl>Elderflower</hl> <div id="content"> <div id="greeting" class="message">Hello! </div> <table> <tr> <td>Custom sign: </ td> <td id="userSign"></ td> </ tr> <tr> <td>Total tiles: </td> <td id="ti l es "></td> </tr> <tr> <td>Subtotal: </td> <td id="subTotal">$</ td> </ tr> <tr> <td>Shipping: </ td> <td id="shipping">$</td> </tr> <tr> <td>Grand total: </td> <td id="grandTotal ">S</td> </tr> </ table> <a href=" D" class="action">Pay Now</ a> </div> <script src="js/ example.js"></ script> </body> </html> @ BASIC JAVASCRIPT INSTRUCTIONS EXAMPLE BASIC JAVASCRIPT IN STRUCTIONS This example combines several techniques that you have seen throughout this chapter. You can see the code fo r this example on the next two pages. Single line comments are used to describe what each section of the code does. To start. three variables are created that store information that is used in the welcome message. These variables are then concatenated (joined together) to create the full message the user sees. The next part of the example demonstrates how basic math is performed on numbers to calculate the cost of a sign. • A variable called sign holds the text the sign will show. • A property called length is used to determine how many characters are in the string (you will meet this property on p128). • The cost of the sign (the subtotal) is calculated by multiplying the number of tiles by the cost of each one. • The grand total is createq by adding $7 for shipping. Finally, the information is written into the page by selecting elements and then replacing the content of that element (using a technique you meet fully in Chapter 5). It selects elements from the HTML page using the value of their id attributes and then updates the text inside t hose elements. Once you have worked your way through this example, you should have a good basic understanding of how data is stored in variables and how to perform basic operations w ith the data in those variable s. BASIC JAVASCRIPT INSTRUCTIONS e EXAMPLE BASIC JAVASCRIPT INSTRUCTIONS c02/example.htm1 llli&ll <!DOCTYPE html> <html> <head> <title>JavaScript & jQuery - Chapter 2: Basic JavaScript Instructions Example</ title> <link rel="stylesheet" href="css/c02.css" /> </head> <body> <hl>Elder fl ower</hl> <div id="content"> <div i d="greeti ng" cl ass="message">Hell o! </di v> <table> <tr> <td>Custom sign: </td> <td id="userSign"></td> </tr> <tr> <td>Total tiles: </td> <td i d="ti l es"></td> </tr> <tr> <td>Subtotal: </td> <td id="subTotal">$</td> </tr> <tr> <td>Shipping: </td> <td id="shipping">$</td> </tr> <tr> <td>Grand total : </td> <td id="grandTotal ">$</td> </tr> </table> <a href=" #" class="action">Pay Now</ a> </div> <script src="js/ example.js"></ script> </body> </html> @ BASIC JAVASCRIPT INSTRUCTIONS A script is made up of a series of statements. Each statement is like a step in a recipe. Scripts contain very precise instructions. For example, you might specify that a value must be remembered before creating a calculation using that value. Variables are used to temporarily store pieces of information used in the script. Arrays are special types of variables that store more than one piece of related information . JavaScript distinguishes between numbers (0 -9), strings (text), and Boolean values (true or false). Expressions evaluate into a single value. Expressions rely on operators to calculate a value. EXAMPLE BASIC JAVASCRIPT INSTRUCTIONS c02/ js/example.js JAVASCRIPT II Create variables for the welcome message var greeting = 'Howdy '; var name = 'Molly'; var message= ', please check your order: ' ; II Concatenate the three variables above to creat e t he welcome message var welcome = greeting + name + message; II Create variables to hold details about the sign var sign = 'Montague House' ; var tiles= sign.length; var subTotal = tiles * 5; var shipping = 7; var grandTotal = subTotal + shipping; II Get the element that has an id of greeti ng var el = document .getElementByid('greeting') ; II Replace the content of that element with the personal ized welcome message el .text Content = welcome; II Get the el ement that has an id of userSign then update its contents var el Sign = document .getElementByld('userSign ' )) elSign .textContent = sign ; II Get the element that has an id of ti l es then update its contents var elTiles = document .getElementByid('tiles'); elTiles .textContent = tiles ; II Get the element that has an id of subTotal then update its contents var elSubTotal = document.getElementByid('subTotal ' ); el SubTotal .textContent = ' $' + subTotal; II Get the element that has an id of shipping then update its contents var elSubTotal = document .getElementByid('shipping') ; el SubTotal .textContent = '$' +shipping; II Get the element that has an id of grandTotal then update its contents var elGrandTotal = document.getElementByid( ' grandTotal ') ; elGrandTotal .textContent = '$ ' + grandTotal; BA SIC J AVASCRIPT INSTRUCTIONS @ A script is made up of a series of statements. Each statement is like a step in a recipe. Scripts contain very precise instructions. For example, you might specify that a value must be remembered before creating a calculation using that value. Variables are used to temporarily store pieces of information used in the script. Arrays are special types of variables that store more than one piece of related information. JavaScript distinguishes between numbers (0 -9), strings (text), and Boolean values (true or false). Expressions evaluate into a single value. Expressions rely on operators to calculate a value. . . .. . Browsers require very detailed instructions about what we want them to do. Therefore, complex scripts can run to hundreds (even thousands) of lines. Programmers use functions, methods, and objects to organize their code. This chapter is divided into three sections that introduce: FU NCTIONS & METHODS OBJECTS BUILT-IN OBJECTS Functions consist of a series of statements that have been grouped together because they perform a specific task. A method is the same as a function, except methods are created inside (and are part of) an object. In Chapter 1 you saw that programmers use objects to create models of the worl d using data, and that objects are made up of properties and methods. In this secti on, you learn how to create your own objects using JavaScript. The browser comes with a set of objects that act like a toolkit for creating interactive web pages. This section introduces you to a number of built-in objects, which you will then see used throughout the rest of the book. .. @ FUNCTIONS, METHODS & OBJECTS FUNCTIONS, METHODS & OBJECTS WHAT IS A FUNCTI ON? Functions let you group a series of statements together to perform a specific task. If different parts of a script repeat the same task, you can reuse the function (rather than rep eating the same set of st atements). Grouping together the statements t hat are required to answer a question or perform a task helps organize your code. Furthermore, the statements in a functio n are not always executed when a page loads, so fu nctions also offer a way to store the steps needed to achieve a task. The script can then ask the function to perform all of those steps as and when they are required. For example, you might have The steps that the function needs to perform in order to perform its task are packaged up in a code block. You may remember from the last chapter that a code block consists of one or more statements contained take a closer look at how to w ri te and use functions in th e pages Some functions need to be provided with info rm ation in order to achieve a given task. For to know its width and height. performing. When you ask it to perform its task, it is known as calling the function. @ t hat follow. after a statement.) example, a functi on to calculate the area of a box would need should describe th e task it is understand the syntax of the example on t he right; you will within curly braces. ( And you do perform if the user clicks on a specific element in the page. later, you need to give your function a name. That name Don't worry if you do not not write a semicolon after the closing curly brace - like you do a task tha t you only want to If you are going to ask the function to perform its task On th e right, there is an example of a function in the JavaScript file. It is called updateMessage () . Pieces of information passed to a function are known as paramet ers. When you write a function and you expect it to provide you Remember that programming languages often rely upon on name/value pairs. The fu ncti on has a name, updateMessage, and t he value is t he code block (which consists of statements). When you call the function by its name, those statement s will run. You can also have anonymous fu ncti ons. They do not have a name, so they cannot be called. with an answer, the response is Instead, they are executed as soon as the interpreter comes known as a return value. across them. ... FUNCTIONS, METHODS & OBJECTS ... A BASIC FUNCTION In this example, the user is You do not need to worry about shown a message at the top of the page. The message is held in an HTML element whose id Before the closing </body> tag, you can see the link to the how this function works yet - you JavaScript file. The JavaScript fi le starts with a variable used will learn about that over the next few pages. For the moment, attribute has a value of message. to hold a new message, and is it is just worth noting that inside The message is going to be followed by a function called updateMessage(). the curly braces of the function changed using JavaScript. are two statements. +:ii.\11 c03/basic-function .html <!DOCTYPE html> <html> <head> <ti t l e>Basic Function TravelWorthy
    We lcome to our site! The HTML for this example is very slightly different than the other examples in this chapter because there is a blackboard which the table is written onto. s DECISIONS & LOOPS You can see the script is added to the page just before the closing tag. EXAMPLE DECISIONS & LOOPS c04/js/ example.js JAVASCRIPT var var var var table = 3; operator= 'addition'; i = 1; msg = ' ' ; if (operator=== 'addition') whi l e (i < 11) { msg += i + ' + ' + table + ' i++; } else { while ( i < 11) { msg += i + ' x ' + table + ' i++; II II II II II II =' II II II = ' II Unit of table Type of calculation (defaults to addition) Set counter to 1 Message If the operator variable says addition While counter is less than 11 + (i +table)+ '
    '; II Calculation Add 1 to the counter Otherwise Whi le counter is less than 11 + (i *table) + '
    '; II Calculation Add 1 to the counter II Write the message into the page var el = document.getElementByid{'bl ackboard'); el .innerHTML = msg; If you read the comments in the code, you can see how this example works. The script starts by declaring four variables and setting values for them. Then, an if statement checks whether the value of the variable called operator is addition. If it is, it uses awhile loop to perform the calculations and store the results in a variable called msg. If you change the value of the operator variable to anything other than addition, the conditional statement will select the second set of statements. These also contain awhile loop, but this time it will perform multiplication (rather t han addition). When one of the loops has finished running, t he last two lines of the script select the element whose id attribute has a value of blackboard, and updates the the page with the content of the msg variable. DECISIONS & LOOPS 8 Conditional statements allow your code to make decisions about what to do next. Comparison operators (===, ! ==, ==, ! =, <, >, <=, =>) are used to compare two operands. Logical operators allow you to combine more than one set of comparison operators. if ... else statements allow you to run one set of code if a condition is true, and another if it is false. switch statements allow you to compare a value against possible outcomes (and also provides a default option if none match). Data types can be coerced from one type to another. All values evaluate to either truthy or falsy. There are three types of loop: for, while, and do ... while. Each repeats a set of statements. The Document Object Model (DOM) specifies how browsers should create a model of an HTML page and how JavaScript can access and update the contents of a web page while it is in the browser window. The DOM is neither part of HTML, nor part of JavaScript; it is a separate set of rules. It is implemented by all major browser makers, and covers two primary areas: MAKING A MODEL OF THE HTM L PAGE ACCESSING AND CHANG ING THE HTML PAGE When the browser loads a web page, it creates a model of the page in memory. The DOM also defines methods and properties to access and update each object in this model, which in turn updates what the user sees in the browser. The DOM specifies the way in which the browser should structure this model using a DOM tree. The DOM is called an object model because the model (the DOM tree) is made of objects. Each object represents a different part of the page loaded in the browser window. s DOCUMENT OBJECT MODEL You will hear people call the DOM an Application Programming Interface (API). User interfaces let humans interact with programs; APls let programs (and script s) talk to each other. The DOM states what your script can "ask the browser about the current page, and how to tell the browser to update what is being shown to the user. 1 I I ~ In each example of this chapter, the JavaScript will amend the HTM L list THE DOM TREE IS A MODEL OF A WEB PAGE As a browser loads a web page, it creates a model of t hat page. The model is called a DOM tree, and it is stored in t he browsers' memory. It consists of four main types of nodes. BODY OF HTML PAGE List

    Buy groceries

    • fresh figs
    • pine nuts honey balsamic vinegar This code shows how a missing image can be used with an HTML attribute to trigger malicious code: Any HTML from untrusted sources opens your site to XSS attacks. But the threat is only from certain characters. @ DOCUMENT OBJECT MODEL DEFENDING AGAINST CROSS-SITE SCRIPTING VALIDATE INPUT GOING TO THE SERVER 1. Only let visitors input the kind of characters they need to when supplying information. This is known as validation. Do not allow untrusted users to submit HTML markup or JavaScript. REQUESTS PAGES FROM AND SENDS FORM DATA TO WEB SERVER •• 2. Double-check validation on the server before displaying user content/storing it in a database. 3. The database may safely This is important because users could bypass validation in the content management system). contain markup and script from trusted sources (e.g., your browser by turning JavaScript off. This is because it does not t ry to process the code; it just stores it. COLLECTS INFORMATION FROM BROWSER AND PASSES IT TO DATABASE STORES INFORMATION CREATED BY WEBSITE ADMINS AND USERS c BROWSER PROCESSES HTML, CSS, AND JAVASCRIPT FILES SENT FROM WEB SERVER WEB SERVER DATABASE GENERATES PAGES USING DATA FROM DATABASE AND INSERTS IT INTO TEMPLATES RETURNS CONTENT NEEDED TO CREATE WEB PAGES ESCAPE DATA COM ING FROM THE SERVER & DATABASE 6. Do not create DOM fragments 5. Make sure that you are only containing HTM L from untrusted sources. It should only be added inserting content generated by 4 . As your data leaves the database, all potentially users into certain parts of the template files (see p230). dangerous characters should be escaped (see p231). as text once it has been escaped. So, you can safely use i nnerHTML to add markup to a page if you have written the code - but content from any untrusted sources should be escaped and added as text (not markup), using properties like textContent. DOCUMENT OBJECT MODEL @ XSS: VALIDATION & TEMPLATES Make sure that your users can only input characters they need to use and limit where this content will be shown on the page. FILTER OR VALIDATE INPUT LIMIT WHERE USER CONTENT GOES The most basic defense is to prevent users from entering characters into form fie lds that they do not need to use when providing that kind of information. Malicious users will not just use
      {color: not here} XSS: ESCAPING & CONTROLLING MARKUP Any content generated by users that contain characters that are used in code should be escaped on the server. You must control any markup added to the page. ESCAPING USER CONTENT ADDING USER CONTENT All data from untrusted sources should be escaped When you add untrusted content to an HTML page, once it has been escaped on t he server, it should still on the server before it is shown on the page. Most server-side languages offer helper funct ions be added to the page as text. JavaScript and jQuery that will strip-out or escape malicious code. both offer tools for doing this: HTML JAVASCRIPT Escape these characters so that they are displayed DO use: textContent or i nnerText (see p216) as characters (not processed as code). DO NOT use: i nnerHTML (see p220) & & ; ' (not ') < < ; > ; " / ; > I ` ; JQUERY DO use: . text () (see p316) DO NOT use: . html() (see p316) JAVASCRIPT N ever include data from untrusted sources in You can still use the i nnerHTML property and jQuery JavaScript. It involves escaping all ASCII characters • html() method to add HTML to the DOM, but you wit h a value less than 256 that are not alphanumeric characters (and can be a security risk). must make sure that: • You control all of the markup being generated (do not allow user content that could contain markup). URLS If you have links containing user input (e.g., links to a user profile or search queries), use the JavaScript encodeURIComponent () method to encode the user • The user's content is escaped and added as text using t he approaches noted above, rather than adding the user's content as HTML. input. It encodes the following characters: , I ? : @ & = + $ # DOCUMENT OBJECT MODEL @ CHECK FOR AN ATTRIBUTE AND GET ITS VALUES Before you work with an attribute, it is good practice to check whether it exists. This w ill save resources if the attribute cannot be found. Using hasAttribute() in an if statement like this means that the code inside the curly braces will run only if the attribute exists on the given element. The hasAttri bute() method of any element node lets you check if an attribute exists. The attribute name is given as an argument in the parentheses. c05/js/get-attribute . js JAVASCRIPT var firstitem = document.getElementByid( ' one'); II Get fi rst l is t item if (firstitem. hasAttribute('class')) { var attr = firstltem.getAttribute(' class'); II If it has class attri bute II Get the att ri but e I I Add the value of the attribute after the l ist var el = document .getElementByid( ' scriptResults'); el .innerHTML = '

      The firs t i tem has a class name : ' iijJiiJil + attr + ''; In this example, the DOM query getEl ementByld () returns the element whose id attribute has a value of one. The hasAtt ribute() method is used to check whether this element has a class attribute, and returns a Boolean. This is used with an if statement so that the code in the curly braces will run only if the cl ass attribute does exist. ThegetAttribute() method returns the value of the cl ass attribute, which is then written to the page. Browser Support: Both of these methods have good support in all major web browsers. DOCUMENT OBJECT MODEL 8 CREATING ATTRIBUTES & CHANGING THEIR VALUES You have seen t his property The setAttri bute() method cl ass attribute. If the attribute used throughout th e chapter to update the status of the allows you t o update the value of any attribute. It takes two does not exist, it will be created and given the specified value. list items. Below, you can see parameters: the attribute name, another way to achieve the task. and the value for the attribute. The cl assName property allows you to change the value of the cOS/js/set-attribute. js JAVASCRIPT var firs tltem = document.getElementByld('one'); II Get the first item firstltem .className = 'complete '; II Change its class attribute var fourthlt em = document.getElementsByTagName('li ').item(3);ll Get fourth item el2.setAttribute('class' , ' cool'); II Add an attribute to it When there is a property (like i;jJiij§I the c 1ass Name or id properties), it is generally considered better to update the properties rather than use a method (because, behind the scenes, the method would just be sett ing the properties anyway). When you update the value of an attribute (especially the c 1 ass attribute) it can be used to trigger new CSS rules, and therefore change t he appearance of the elements. Note: These techniques override the entire value of t he cl ass attribute. They do not add a new value to the existing value of the cl ass attribute. If you wanted to add a new value onto the existing value of the c 1ass attribute, you would need to read the content of the attribute first, then add the new text to that existing value of the attribute (or use the jQuery . addCl ass () method covered on p320). @ DOCUMENT OBJ ECT MODEL REMOV ING ATTRI BUTES To remove an attribute from an element, first select the element, then call removeAtt r i bute () . It has one parameter: the name of the attribute to remove. JAVASCRIPT Trying to remove an attribute that does not exist w ill not cause an error, but it is good practice to check for its existence before attempting to remove it. In this example, the get El ementByld () method is used to retrieve t he first item from this list, which has an id attribute with a value of one. c05/ j s/ remove-at tri bute.js var firstltem = document .getElementByld{'one ' ) ; // Get the first i tem if (firstltem.hasAttribute('class ')) { // If it has a class attri bute firstl t em. removeAttri bute( ' cl ass' ) ; // Remove its cl ass attribute The script checks to see if the selected element has a c 1ass attribute and, if so, it is removed. DOCUMENT OBJECT MODEL @ EXAM INING THE DOM IN CHROME Modern browsers come with tools that help you inspect the page loaded in the browser and understand the structure of the DOM tree. Each of these object names has an arrow next to it which you can use to expand that section. It will tell you what properties are available to that kind of node. They are separated because some properties are specific to list item elements, others to element nodes, others to all nodes, and others to all objects, and the different properties are listed under the corresponding type of node. But they do remind you of which properties you can access through the DOM node for that element. 8 DOCUMENT OBJECT MODEL .,.• e e e / D i.vaScrlp< , JQutry - Ch• x '\u c ~ ~ 01 - N- ~ D file:/ I/initial- page.html v•• 1 Resources T . SOUf CC:S Timtlln< Profiles Audiu ~ In the screenshot to the right, the element is highlighted and the Properties panel ( 1) indicates that this is an: • 1 i element with an id attribute whose value is one and cl ass whose value is hot • an HTMLLI Element • an HTMLElement • an element • a node • an object - = O Show inhe ritec .- Computed Style .,Styles ... - • •

      List King

      8uy grocer ies

      't[_, Consol• + •i;; 0· ,. Metrics !i" Propenles • \itlone. hot \. 1 .I • KTMLl.lE te11ent • • KTMLEte11ent f resh • E\nent .. figs" •Node <\i i d•"two" c l ass• "hot">pine nuts
    • l\oney <\i id•'•four .. >batsamic vinegar ,. Event Listeners
    ~ >:: Q. !.- Objeelements and updating the value of the c 1ass attribute to coo 1. 3: Add the number of list items to the heading This involves four steps: 1. Reading the content of the heading 2 . Counting the number of <:l i >elements in the page 3. Adding the number of items to the content of the heading 4 . Updating the heading with this new content DOCUMENT OBJECT MODEL § EXAMPLE DOCUMENT OBJECT MODEL c05/ js/ example. js JAVASCR I PT II ADDING ITEMS TO START AND ENO OF LIST var list = document .get El ementsByTagName( ' ul ')[OJ; II Get the el ement II ADD NEW ITEM TO END OF LIST var newitemLast = document . createElement('li '); var newTextLast = document .createTextNode{'cream'); newitemLast.appendChild(newTextLast); list.appendChild(newitemLast); II II II II Create element Create text node Add text node to element Add element end of lis t II II II II Create element Create text node Add text node t o element Add element to list II ADD NEW ITEM START OF LIST var newitemFirst = document . createElement('li ') ; var newTextFirst = document.createTextNode('kale'); newitemFirst.appendChild(newTextFirst); list . insertBefore(newitemFirst, list . firstChild); This part of the example adds two new list items to the